Anonymous Methods in C#

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.

Advertisement

April 9, 2007. .Net.

Leave a Comment

Be the first to comment!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Trackback URI

Follow

Get every new post delivered to your Inbox.