Thursday, January 3, 2008

[.NET] Events and Delegates

Lately I've been reflecting about Events and delegates in the .NET framework: to my understanding event is actually not a type, just a keyword.

Quoting from MSDN:

The event keyword lets you specify a delegate that will be called upon the
occurrence of some "event" in your code. The delegate can have one or more
associated methods that will be called when your code indicates that the event
has occurred.


You can specify your own events, but in order to specify events and handle them you should:
//1) declare a delegate:
public delegate void myEventHandler(object sender, AlarmEventArgs e);
//2) "declare" an event on your delegate
//(read the first sentence from the quote now):
public event myEventHandler myEvent;
//3)Wire event and SomeMethod through the event delegate
//(At some initialization stage)

myControl.myEvent += new myEventHandler(SomeMethod);

You can do this without explictly declaring a delegate and event if you are using .NET built in controls, because they already have their own events and delegates (EventHandler - which uses a generic System.EventHandler delegate) declared so you can just wire an event to SomeMethod using the generic delegate called EventHandler, like this:

button.Click += new EventHandler(this.Button_Clicked);

Where button is the name of the control, Click is the event and Button_Clicked is the name of your method.

This stuff is not-so-easy-to-catch, so hope it might help someone.

2 comments:

Anonymous said...

Nice post

Anonymous said...

Keep up the good work.