Events can be of any delegate type, not just EventHandler
and EventHandler<T>
. For example:
//Declaring an event
public event Action<Param1Type, Param2Type, ...> EventName;
This is used similarly to standard EventHandler
events:
//Adding a named event handler
public void HandlerName(Param1Type parameter1, Param2Type parameter2, ...) {
/* Handler logic */
}
EventName += HandlerName;
//Adding an anonymous event handler
EventName += (parameter1, parameter2, ...) => { /* Handler Logic */ };
//Invoking the event
EventName(parameter1, parameter2, ...);
It is possible to declare multiple events of the same type in a single statement, similar to with fields and local variables (though this may often be a bad idea):
public event EventHandler Event1, Event2, Event3;
This declares three separate events (Event1
, Event2
, and Event3
) all of type EventHandler
.
Note: Although some compilers may accept this syntax in interfaces as well as classes, the C# specification (v5.0 ยง13.2.3) provides grammar for interfaces that does not allow it, so using this in interfaces may be unreliable with different compilers.