Posted by: rhwilburn | February 13, 2009

Event Handling Techniques

As .NET grows so do the number of ways of tackling the same or similar problems. Event Handling is no exception.

//1
button1.Click += new RoutedEventHandler(button1_Click);
 
//2
button1.Click += button1_Click;
 
//3
button1.Click += delegate(System.Object o, RoutedEventArgs e)
                     {
                         System.Windows.MessageBox.Show("Click!");
                     };
 
//4
button1.Click += delegate
{
    MessageBox.Show("Click!");
};
 
//5
button1.Click += (o, e) => MessageBox.Show("Click!");

 

Personally I use approach 2 and 5 depending on the situation. Approaches 3, 4 & 5 are anonymous handlers which means that their name is determined at creation (so we don’t know what it is). This can sometimes be an issue if you want to unsubscribe from an event, see here. Again with this post Resharper will make suggestions to use approach 2 and 5.

I feel there is an important difference between approach 1 and 2 that should be elaborated on. Approach 1 delcares the delegate of RoutedEventHandler twice because the delegate is already specified in, and hence inferred from, the event declaration. This is shown below:

internal event RoutedEventHandler Click;

 

Inferring types rather than having duplicate definitions is important as it means that you don’t have to repeat yourself and when you refactor your code you will have an easier job updating it when it is specified once.

For those unfamiliar with delegates, delegates are method parameter contracts which in the case of RoutedEventHandler specifies that an implementer of its contract will have the parameters of (Object, RoutedEventArgs).


Leave a response

Your response:

Categories