BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 2.0+

C# Anonymous Methods

C# allows the declaration of delegates. These hold method references that may be changed at run-time and are essential for creating events. It is often the case that the delegate is never changed. In these cases, anonymous methods can simplify code.

What is an Anonymous Method?

Delegates are a very useful part of the C# language. A delegate, with or without parameters, can be declared in C# code in a similar manner to a method, except that it contains no code block. The delegate can be used to reference a named method, which will be executed when the delegate is called. This leads to a great deal of flexibility, particularly as you can change the delegate's referenced method at run-time.

An understanding of the use of delegates is also essential when creating and consuming events. An event declared within a class is always based upon a delegate. When other classes subscribe to the event, the methods to call on the raising of the event are held in the underlying delegate.

Delegates can also used as parameters to some standard methods. A good example is the Sort method of the generic List class in the .NET framework version 2.0. One of the overloaded variations of this method accepts a Comparison delegate. The delegate provided must reference a method that performs a comparison of two items and determines if they are equal and, if they are not, which is the larger. This delegate is executed as many times as required to sort the collection according to the developer's requirements.

Sometimes a method is created to be referenced by a delegate but is only used once. This can seem to be unnecessarily complicated and, for simple methods, can reduce the readability of the code. In these situations, it may be preferable to use anonymous methods. An anonymous method is a code block inserted into the program in place of a delegate. It removes the requirement to create a named method elsewhere in the code.

Using Anonymous Methods

In the following sections we will demonstrate anonymous method usage with some examples. The same examples can be found in the source code that can be downloaded using the link at the top of the page.

Simple Anonymous Methods

The simplest form of anonymous method is one that requires no parameters. These can be used to replace delegates that also do not use parameters. A good example of this is with one way of starting a new thread. Normally a method will be created that contains the code to be run by the new thread. A Thread object may then be instantiated using a constructor that accepts a delegate as its parameter. The delegate identifies the method that is executed when the thread is started.

A simple example may consist of these two elements as shown in the code below. Firstly, the method containing the code is created. In this example, the method simply shows a message before it completes:

private void ThreadCode()
{
    MessageBox.Show("New Thread!");
}

To create and start the new thread to execute this method, the following code may be used:

Thread newThread = new Thread(ThreadCode);
newThread.Start();

This creates a new thread, passing the method as its delegate parameter. Starting the thread executes the "ThreadCode" method concurrently with the rest of the program.

The anonymous method version of the above code is simpler to read, as it does not require the creation of the "ThreadCode" method. Instead, the delegate keyword, followed by an empty set of parentheses () and a code block containing the code to execute, is used to replace the delegate in the constructor.

Thread newThread = new Thread(delegate() { MessageBox.Show("New Thread!"); });
newThread.Start();

For short methods, this syntax can simplify the code dramatically. For more complex delegates or if the anonymous method is to be used more than once, it can be more appropriate to declare a delegate object. This object can then be assigned an anonymous method, rather than a method reference. Using this alternative approach, the previous example becomes:

ThreadStart threadCode = delegate() { MessageBox.Show("New Thread!"); };

Thread newThread = new Thread(threadCode);
newThread.Start();

Note the use of the ThreadStart delegate type in the declaration. This is the type of delegate that must be used when creating threads that execute methods without parameters.

Anonymous Method Parameters

As mentioned previously, event handlers make use of delegates that reference the methods to be called when the event is raised. If the referenced method is only used in one place, it may be a good candidate for replacement with an anonymous method.

To demonstrate, create a new Windows Forms application and add a button to the automatically created form. Name this button "AnonParamsButton". In Visual Studio, if we want the button to react to being clicked, we can double-click the button in the designer. This adds the code to capture the Click event and link it to a method using a delegate.

The resultant code for adding the referenced method to the event's delegate would look similar to that shown below. NB: When using Visual Studio this is added to the automatically generated designer code in the form's ".designer.cs" file.

this.AnonParamsButton.Click += new System.EventHandler(this.AnonParamsButton_Click);

You can see that this code creates a new EventHandler delegate that references a method named "AnonEventButton_Click". This is the default name generated by Visual Studio. A new method stub will also be created, to which we can add the code to be executed when the event is raised. This may be similar to that below:

private void AnonParamsButton_Click(object sender, System.EventArgs e)
{
    MessageBox.Show("Click!");
}

The anonymous method version of this code is simpler as it does not require the creation of a new method. Instead, an anonymous method is used to replace the EventHandler delegate. If you have added the two sections of code shown above, remove them. Instead, add the following code to the bottom of the form's constructor:

AnonParamsButton.Click += delegate(object sender, System.EventArgs e)
{
    MessageBox.Show("Click!");
};

This example shows the syntax of an anonymous method declaration with parameters. As before, the delegate keyword is used but this time it is followed by the parameters that the method requires within the parentheses. In this case, these must match the standard parameters of the EventHandler delegate. A code block is then opened and the desired code added.

29 June 2008