
.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.
29 June 2008