Saturday, November 03, 2007

Event Accessors in C#

We all know how to create a new event and add a event handler for it. The "+ = " syntax is most familiar with .Net developers. But what happens when you actually do this ?? What if you want to do some processing when you add a handler ??? What is you want to control what actually happens when an event handlers is added ??

This is where event accessors comes to play.

The syntax of doing it is also very similar to the Property get/set. The only difference is that here we are adding/removing instead of get/set.

private event EventHandler myPrivateEvent;

public event EventHandler MyEvent
{
add
{
System.Diagnostics.Debug.WriteLine("added");
myPrivateEvent+= value;
}
remove
{
myPrivateEvent-= value;
System.Diagnostics.Debug.WriteLine("removed");
}
}


Now this can be explored to accomplish betters needs when adding events .