tags:

views:

286

answers:

4

I currently have a page which is declared as follows:

public partial class MyPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //snip
        MyButton.Click +=
            (o, i) =>
            {
                //snip
            }
    }
}

I've only recently moved to .NET 3.5 from 1.1, so I'm used to writing event handlers outside of the Page_Load. My question is; are there any performance drawbacks or pitfalls I should watch out for when using the lambda method for this? I prefer it, as it's certainly more concise, but I do not want to sacrifice performance to use it. Thanks.

+5  A: 

There are no performance implications since the compiler will translate your lambda expression into an equivalent delegate. Lambda expressions are nothing more than a language feature that the compiler translates into the exact same code that you are used to working with.

The compiler will convert the code you have to something like this:

public partial class MyPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //snip
        MyButton.Click += new EventHandler(delegate (Object o, EventArgs a) {
                //snip
            });
    }
}
Andrew Hare
I see. So is there also no drawback from having these handlers inside of Page_Load versus having them outside of it?
lush
The prevailing convention is to attach event handlers in the `OnInit` method but since a button's `Click` event will be raised after the page loads this example is fine.
Andrew Hare
A: 

No performance implications that I'm aware of or have ever run into, as far as I know its just "syntactic sugar" and compiles down to the same thing as using delegate syntax, etc.

kekekela
+2  A: 

Performance-wise it's the same as a named method. The big problem is when you do

    MyButton.Click -= 
        (o, i) => 
        { 
            //snip 
        } 

it will probably try to remove a different lambda, leaving the original one there. So the lesson is that it's fine unless you also want to be able to remove the handler.

Gabe
A: 

EventHandler handler = (s, e) => MessageBox.Show("Woho");

button.Click += handler; ... button.Click -= handler;

usama wahab khan