Using lambda expressions for event handlers

I currently have a page that 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 just recently switched to .NET 3.5 from 1.1, so I'm used to writing event handlers outside of Page_Load. My question is: are there any performance flaws or pitfalls that I have to consider when using the lambda method for this? I prefer this because it is, of course, more concise, but I do not want to sacrifice the results in order to use it. Thank.

+83
performance c # lambda events
Mar 17 '10 at 18:56
source share
4 answers

There are no performance implications as the compiler translates your lambda expression into an equivalent delegate. Lambda expressions are nothing more than a language function that the compiler translates into the same code that you work with.

The compiler will convert the code that you have, 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 }); } } 
+83
Mar 17 '10 at 18:58
source share

In performance, it will be the same as the named method. The big problem is this:

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

He will probably try to remove another lambda, leaving the original there. So the lesson is that this is great if you also don't want to remove the handler.

+44
Mar 17 '10 at 18:59
source share
 EventHandler handler = (s, e) => MessageBox.Show("Woho"); button.Click += handler; button.Click -= handler; 
+29
06 '10 at 9:19
source share

The lack of performance implications that I know of or have ever encountered, as far as I know, is just “syntactic sugar” and compiles with the same role as using delegate syntax, etc.

+2
Mar 17 '10 at 18:58
source share



All Articles