The Shortest Event Handler Syntax

Posted on January 13, 2007  |  

Posted in Development

4 comments

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
}

4 comments

Shane Shepherd
on January 15, 2007

@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?


csharp guy
on January 15, 2007

wow excellent :).

I missed it too thanks for sharing


Milan Negovan
on January 16, 2007

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.


ASPCode.net
on January 20, 2007

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;


Leave a comment

  •