-1

i would like to know if there is a way to work with Events in a generic way.

Firty My Class inherit EventArgs

   public class DeviceMessage : EventArgs
{
    public Devices devices;

    public DeviceMessage(Devices devices)
    {
        this.devices = devices;
    }
}

My Class Events

public static class CommunicationEvent
{
    public static event EventHandler<DeviceMessage> SendWeb;

    public static void SendMessageToWeb(DeviceMessage arg)
    {
        if (SendWeb != null)
            SendWeb(null, arg);
    }
}

the way it is implemented is functional, because where I call the event I pass "DeviceMessage", but what I need is for the event to be generic, I can pass other classes "TankMessage", "MonitorMessage".

Not Working -

public static event EventHandler<TEventArgs> SendWeb;
  • 1
    Events can't be generic, just like properties can't be generic. You can make the enclosing type generic or rewrite the code. – Aluan Haddad Jan 22 '21 at 22:13

1 Answers1

0

Declare the type parameter at the class level.

public static class CommunicationEvent<T> where T : EventArgs
{
    public static event EventHandler<T> SendWeb;

    public static void SendMessageToWeb(T arg)
    {
        if (SendWeb != null)
            SendWeb(null, arg);
    }
}
John Wu
  • 50,556
  • 8
  • 44
  • 80
  • where T : EventArgs , CS0699: ComunicationEvent does not define type parameter 'T' – Rodrigo Costa Jan 25 '21 at 13:34
  • i change for TEventArgs it's works – Rodrigo Costa Jan 25 '21 at 14:04
  • While the code in this answer will _compile_ it is no way semantically equivalent to what the original question asked for. In particular, rather than there being a single event for which differently-typed subscribers can be used, there is a different event for each different type `T` that is used. While it's true that the former isn't safe or practical (per the duplicate questions...this question has already been answered multiple times), posting an answer to a _different question_ is not useful, especially if there is also no explanation of why one answered a different question than asked. – Peter Duniho Jan 25 '21 at 18:06