Using lambda expressions for event handlers

C#PerformanceEventsLambda

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

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.

Solution 3 - C#

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

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

Solution 4 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChristopher GarciaView Question on Stackoverflow
Solution 1 - C#Andrew HareView Answer on Stackoverflow
Solution 2 - C#GabeView Answer on Stackoverflow
Solution 3 - C#usama wahab khanView Answer on Stackoverflow
Solution 4 - C#heisenbergView Answer on Stackoverflow