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?

2 Comments

Comments have been disabled for this content.