TechnicalArchitectureWorx

The (Unofficial) ITWorx Technical Architecture Blog

Anonymous Methods in C#

Posted by archworx on May 23, 2007

In .Net v1.x, declaration of delegate required named methods. C# 2.0 introduced anonymous methods, as MSDN states, “Creating anonymous methods is essentially a way to pass a code block as a delegate parameter.

// Create a handler for a click event
btn.Click += delegate(System.Object o, System.EventArgs e) { MessageBox.Show("Click!"); };

This can be very useful in some cases such as a parameter to the Thread constructor:

new System.Threading.Thread(
  delegate()
  {
      System.Console.WriteLine("Hello");
      System.Console.WriteLine("World");
  }).Start();

Click here for more info.

One Response to “Anonymous Methods in C#”

  1. Luc said

    Another great use is when using the ForEach method of a List like this:

    string UserList = "";
    List MyUsers = GetUsers();
    MyUsers.ForEach(delegate(User theUser)
    {
    UserList += theUser.Name + " (" + theUser.Email + ")\n";
    });

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 )

Google+ photo

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

Connecting to %s

 
%d bloggers like this: