#595 – Syntax Choices for Defining an Event Handler

There are several different syntaxes that you can use when specifying an event handler in code.  (This is assuming that you’re using a CLR event wrapper, rather than calling UIElement.AddHandler directly).

The most common syntax for defining an event handler is to declare a new instance of the appropriate handler type, passing it the name of a preexisting method.  Since the handler type is a delegate, you’re passing the name of a method to the delegate’s constructor.

myButton.Click += new RoutedEventHandler(myButton_Click);
myTextBox.KeyDown += new KeyEventHandler(myTextBox_KeyDown);

As a shortcut, you can just use the name of the method (your handler).

myButton.Click += myButton_Click;
myTextBox.KeyDown += myTextBox_KeyDown;

Instead of defining a separate method, you can just specify an anonymous method, with or without arguments.

            myButton.Click += delegate { Trace.WriteLine("Hey, you clicked a button"); };
            myTextBox.KeyDown += delegate(object sender, KeyEventArgs e) { Trace.WriteLine(string.Format("sender: {0}", sender)); };

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

3 Responses to #595 – Syntax Choices for Defining an Event Handler

  1. My vote for just using the name of the method .

  2. Bruno says:

    Or even simpler with a lambda:

    myTextBox.KeyDown += (o, e) => { Trace.WriteLine(string.Format(“sender: {0}”, sender)); };

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: