#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)); };