Event handling with anonymous methods in C# 2.0

Nov 12, 2006

One of the nicest things about the new anonymous methods is how simple event handling has become. Here is an example of how we used to handle events. It demonstrates how to add an event handler to the btnSave’s Click event and assign a method to handle it.

protected void Page_Load(object sender, EventArgs e)

{

  btnSave.Click += new EventHandler(btnSave_Click);

}

 

void btnSave_Click(object sender, EventArgs e)

{

  DoSomething();
}

The next approach uses anonymous method to do exactly the same thing.

protected void Page_Load(object sender, EventArgs e)

{

  btnSave.Click += delegate { DoSomething(); };
}

This will save a lot of code lines.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Comments (6) -

 Dan Atkinson
Dan Atkinson
11/13/2006 12:45:40 PM #

Hey there!

I totally forgot about this approach!

Although, from a maintainability point of view, I prefer the first method, it is a LOT easier to just do the anonymous method.

 Ramy Mahrous
Ramy Mahrous
11/14/2006 12:05:14 AM #

I just want to ask when to use and to not use [ anonymous methods in  handling events ] from performance's point of view

Mads Kristensen
Mads Kristensen
11/14/2006 6:18:44 AM #

Ramy, I don't think there are any performance hits by using anonymous methods or not. I think the compiler ends up with roughly the same code for both of them. I haven't checked though.

 Salman
Salman
11/15/2006 6:35:25 PM #

Yeah it does reduce the number of lines of code, but I find it is a little 'harder' to read.

 Steve
Steve
3/30/2007 9:00:24 PM #

What if you need to do something with the event args parameter. Is it still possible access this?

Issa Qandil
Issa Qandil Jordan
3/22/2008 5:30:28 AM #

Yea please answer the above questions Laughing

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.