A look at the anonymous methods in C#
Hi

You must be aware of delegates if you have worked in C# before. Even then let me describe delegates my way. Delegates are objects that encapsulate the reference to functions. Implementation of Event Handler code is one of the best examples of delegates.

When we double click on a button on the form to add the handler for that button’s click event, the windows form generate two separate codes. The actual event Handler and a hidden code (found in the designer code) to wire-up the button clicks event.

The code outputted is like this.

private void button1_Click(
  object sender, System.EventArgs e)
{ }

and

this.button1.Click +=   new System.EventHandler(
  this.button1_Click);

[Note: The Signature for the button click event handler is defined in the System.EventHandler delegate]

We can simplify this a bit by using anonymous method. We can create the whole handler method inline without defining a method name. We will still require the patameters.

this.button1.Click += 
  delegate(object sender, EventArgs e)
  {    };

Here you can see there is no method name and we are not delegating the event to another method instead writing the method inline.

[Note: That there is a semicolon in the end of the method, since this is just one line of code]

Hope this helps
Thanks
Vikram


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Posted on 10/6/2006 7:09:02 AM

I don't think there is any major benefit to this other than a few cycles. The former method allows you quick access to the button click function through the Class/Project Trees. Whereas, the latter method can create a long function that includes many complex delegated functions within it, which can get very ugly quickly.

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2008 Vikram Lakhotia