Search code examples
c#event-handlinganonymous-methods

Difference between EventArrivedEventHandler and EventHandler?


I tried to create a USB controller class and just tried to expose my internal EventArrivedEventHandler from ManagementEventWatcher to allow the consumer to do something if a USB is detected.

I had expected to be able to cast the EventArrivedEventHandler to a EventHandler, as they are all just delegates... but apparently not.

Is there a reason why this is not possible?

EDIT: I have found an approach that lets me do what I wanted very cleanly.

_watcher.EventArrived += (sender, eventArgs) => DeviceDetected?.Invoke(null, null);

Solution

  • The reason why this is not possible is that EventArraivedEventHandler and EventHandler have different signatures. As you can see, the EventArrivedEventHandler take as second argument EventArrivedEventArgs and not EventArgs as EventHandler does.

    public delegate void EventArrivedEventHandler(object sender, EventArrivedEventArgs e)
    

    In theory it should be possible to cast this to an EventHandler<EventArrivedEventArgs>.

    Visit the MSDN Page for EventArivedEventHandler and EventArrivedEventArgs for further details about this issue.