Three related idioms: event, delegate, event-handler. I always get confused by who is \"added\" to who.
event += handler
event += delegate
handler += delegate
>
Here is my summary (please correct me if I'm wrong):
delegate
is a pointer to a method (instance\static)
eventHandler
is a delegate with a specific signature (sender, eventArgs)
event
is an abstraction of accessing a delegate of any type, but it's usually an eventHandler
by convention
//We declare delegates as a new type outside of any class scope (can be also inside?)
public delegate retType TypeName (params...)
//Here we assign
public TypeName concreteDeleagteName = new TypeName (specificMethodName);
//Declaring event
//a. taken from http://stackoverflow.com/questions/2923952/explicit-event-add-remove-misunderstood
private EventHandler _explicitEvent;
public event EventHandler ExplicitEvent
{
add
{
if (_explicitEvent == null) timer.Start();
_explicitEvent += value;
}
remove
{
_explicitEvent -= value;
if (_explicitEvent == null) timer.Stop();
}
}
//or: b.auto event - the compiler creates a "hidden" delegate which is bounded to this event
public event TypeName eventName;
I want to recommend the great article Event Handling in .NET Using C#.
So we can only attach (eventName):
eventName += new TypeName (specificMethodName);
Which is equivalent to (_eventName is a delegate\eventHandler):
_eventName += new TypeName (specificMethodName);