Non-Standard Event Declaration C# with Example



Non-Standard Event Declaration C# with Example

Events can be of any delegate type, not just EventHandler and EventHandler. For example: 
//Declaring an event 
public event Action 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. 

0 Comment's

Comment Form

Submit Comment