I've created an event which is executed every time my USB device is connected/disconnected.
//Event for USB disconnect
public delegate void DeviceDisconnectedHandler();
public event DeviceDisconnectedHandler DeviceDisconnected;
It works just fine but I want to execute some code internal to the class that's generating the event every time this happens. I thought maybe I could just add this to the delegate like...
public delegate void DeviceDisconnectedHandler(){
//Do some stuff first <-- inside of delegate
}... but the compiler doesn't seem to like this.
I know that since the event isn't fired until I actually call DeviceDisconnected(), I could simply do the following...
//Do some stuff first <-- outside of delegate
DeviceDisconnected();
... but it doesn't look as clean to me and this also indicates I don't understand Events/Delegates too well.

2 answers
A delegate declaration is just a template which tells the system which methods (by return type and number/type of parameters) can be called via an object of the delegate type. As such the delegate has no body and so you can't include any code in the declaration.
An event is just a delegate which only allows certain operations to be done to it from outside the class in which it is defined. Those operations are adding or removing eventhandler methods using (from C#) the += and -= operators respectively. When the event is fired (by calling the delegate), the eventhandlers are all called in the order they were added to its invocation list.
If you want to execute some code each time the event fires, then I'd do that in the method which is called to fire it:
answered 2 years ago by:
17279
There is a pattern that should always be followed when defining your own events.
public CustomClass {public event EventHandler<CustomEventArgs> CustomEvent;
}
public CustomClass {
public event EventHandler<CustomEventArgs> CustomEvent;
protected virtual void OnCustomEvent( CustomEventArgs e) {
// before event logic here
if( CustomEvent != null ) CustomEvent( this, e );
// after event logic here
}
}
answered 2 years ago by:
2309