Anonymous Methods (C# Programming Guide)

http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx

Anonymous Methods (C# Programming Guide)

Visual Studio 2010

Other Versions

·Visual Studio 2008

·Visual Studio 2005

In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods as the preferred way to write inline code. However, the information about anonymous methods in this topic also applies to lambda expressions. There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions. For more information specifically about lambda expressions, see Lambda Expressions (C# Programming Guide).

Creating anonymous methods is essentially a way to pass a code block as a delegate parameter. Here are two examples:

VB

C#

C++

F#

JScript

Copy

// Create a handler for a click event.

button1.Click += delegate(System.Object o, System.EventArgs e)

{ System.Windows.Forms.MessageBox.Show("Click!"); };

VB

C#

C++

F#

JScript

Copy

// Create a delegate.

delegate void Del(int x);

// Instantiate the delegate using an anonymous method.

Del d = delegate(int k) { /* … */ };

By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method.

For example, specifying a code block instead of a delegate can be useful in a situation when having to create a method might seem an unnecessary overhead. A good example would be when you start a new thread. This class creates a thread and also contains the code that the thread executes without creating an additional method for the delegate.

VB

C#

C++

F#

JScript

Copy

void StartThread()

{

System.Threading.Thread t1 = new System.Threading.Thread

(delegate()

{

System.Console.Write("Hello, ");

System.Console.WriteLine("World!");

});

t1.Start();

}

Remarks

Advertisements

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