Anonymous delegates for event handling

Let's start off the new year with a question. Traditionally here’s how you would code up an event handler for say a button on a Windows form (ignore the fact there are presenters and such and how they got initialized). 

   56         protected override void OnLoad(EventArgs e)

   57         {

   58             btnClose.Click += new EventHandler(btnClose_Click);

   64             _presenter.OnViewReady();

   65         }

   67         void btnClose_Click(object sender, EventArgs e)

   68         {

   69             _presenter.OnCloseView();

   70         }

That's all well and fine. The form loads, the event handlers are registered and the view is called. There's a method for each event setup (by default in the form of ControlName_EventName) so you might have dozens of additional methods in your view code depending on how complex the form is.With .NET 2.0 we can use anonymous delegates so the code above can become this:

   56         protected override void OnLoad(EventArgs e)

   57         {

   61             btnClose.Click += delegate { _presenter.OnCloseView(); };

   64             _presenter.OnViewReady();

   65         }

Just setup the delegate in the load method for the form. Same rules apply as in the presenter method will get called when the button is clicked.I like the second method as in it's cleaner and I don't have to clutter up my view code with lots of methods that only pass thru to a presenter. Even with dozens of events on dozens of controls I would only have one line for each in my OnLoad method. It's not just reducing the number of lines of code but readiblity that's key here.

So any thoughts on these two approaches? Preferences? Ideas? Comments? Small unregistered marsupials?

Published Monday, January 01, 2007 7:09 AM by Bil Simser

Comments

# re: Anonymous delegates for event handling

Monday, January 01, 2007 2:34 PM by Dan

I've been moving towards a much more event driven model in my ASP.Net pages - i.e., click event calls a validation method, which then raises either a ValidDataEntered or InvalidDataEntered event.  I haven't been able to get into the MVC/MVP ideas for the programming that I do, but that's another discussion.  The implementation of what I'm doing is very similar to what you've got, but sometimes I have more than one event handler if an underlying method needed to be called as both an EventHandler and say a GridViewCommandEventHandler.  Your suggestion here may eliminate the need for that!

Thanks!

# re: Anonymous delegates for event handling

Monday, January 01, 2007 3:43 PM by Sean

one of the disadvantages for anonymous delegates is when you debug, you see a funky name in the call stack. Once get used to this, it doesn't matter that much.

# re: Anonymous delegates for event handling

Monday, January 01, 2007 5:37 PM by Gabriel Lozano-Morán

This is a nice example on why this feature has been implemented.