Anonymous Methods

So I digress a little bit. Anonymous methods were new to C# 2, not C# 3. However, they aren't in common use so I thought I'd go into explaining them here, as they are fundamentally important on our journey of learning LINQ.

So as a developer you're familiar with the concept of methods. Named Logical blocks of code that are grouped together, can take input parameters, do stuff, and return values.
The definition of "Anonymous" (according to Merriam-Webster) is "not named or identified".

So we can see here there's a bit of a conflict... although it's not as difficult as it looks! :)

We go from the following well established piece of code:

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

void button1_Click(object sender, EventArgs e)
{
   MessageBox.Show("Test");
}

to our new Anonimised version:

this.button1.Click += delegate
{
   MessageBox.Show("Test");
};

 

It's important to realise here that Anonymous methods are purely syntactical. They still compile down to real methods. In this instance opening up Reflector (amazing tool, no one should be without it) shows that the anonymous method has been (rather imaginatively) named <.ctor>b__0. It's called from the constructor and behaves just like a normal method. They can be useful to keep code close to where it is used (in the example of keeping it near the definition for the button in this case) and also for multithreading purposes:

void StartThread()
{
    System.Threading.Thread t1 = new System.Threading.Thread
      (delegate()
            {
                System.Console.Write("Hello, ");
                System.Console.WriteLine("World!");
            });
    t1.Start();
}

The above example prints "Hello World!" asynchronously on the command line

They have more uses, as we'll find out later! :)

---

Extensions methods are a new language feature of C# 2 and require .net 2.0 to function

Published 23 April 2008 22:29 by Mat Steeples

Comments

# C# 3 (aka .NET 3.5, Microsoft Visual Studio 2008)@ 23 April 2008 22:34

I started a series over a week ago about the new language features in C# 3 and the capabilities of version

Mat Steeples

Leave a Comment

(required) 
(required) 
(optional)
(required)