Skip navigation.

Microsoft AJAX Library Cheat Sheets: Foxit Reader RepackAll recent postsHttpRequest.Params - A Helpful Quad

The Shortest Event Handler Syntax

I don’t know how I missed this! In ASP.NET 1.x you wired event handlers as follows (assuming Submit is a button):

Submit.Click += new EventHandler(Submit_Click);
…
void Submit_Click(object sender, EventArgs e)
{
    // Handle the click
}

In 2.0, anonymous delegates come in handy when event handlers are short enough.

Submit.Click += delegate (object sender, EventArgs evt) {
   // Handle the click
};

is the same is

Submit.Click += delegate {
   // Handle the click
};

But I slapped myself on the forehead when I saw this “shorthand” syntax, which is equivalent to the first example:

Submit.Click += Submit_Click;
…
void Submit_Click(object sender, EventArgs e)
{
    // Handle the click
}

Comments

Comment permalink 1 Shane Shepherd |
@Milan,

Let me see if I have this right...

In your code-behind you can put

Submit.Click += Submit_Click;

at the root of your class...and this handles the same job as a onclick="Submit_Click" in your .aspx page? If so, cool. Is there an advantage to either the programmatic or the declarative method of doing this?
Comment permalink 2 csharp guy |
wow excellent :).

I missed it too thanks for sharing
Comment permalink 3 Milan Negovan |
Shane, I don't think there's a difference. It should compile down to the same code. It's just a shorter notation and less typing.
Comment permalink 4 ASPCode.net |
Cool! Didn't know that works for event handlers as well. I am just getting "used to" using delegates and anonymous functions for Collection.Find etc. Also thanks for Submit.Click += Submit_Click;

Emails and Notifications

Would you like to be notified when somebody responds to this post?  Would you like to have these comments emailed to you?

TrackBacks

Sorry, TrackBacks are not allowed.

Submit your comment

Please enter only text since all HTML tags except hyperlinks will be stripped. Hyperlinks will become live links. Any comments with flaming or offensive language will be deleted. Be courteous to other posters. Thank you.

Your name (required):
Your email (optional):
Your site's URL (optional):
Enter this number
Type in the number above:
Comment (required):