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.

Outer Variables

Anonymous methods provide an additional benefit to standard delegates. They are allowed to access the local variables of the class member in which they are declared. When used in this way, the local variables of the containing member are called outer variables.

Once captured, the outer variable's life is extended to match the lifetime of the anonymous method, even when the local variable in the containing method goes out of scope. The compiler actually creates a new class to hold outer variables and a reference to each is captured in an object of this class at the time of the delegate's creation. A delegate may not use the containing member's variables if they have been passed by reference or as output parameters.

The following example requires an additional button on the example form. Add a new button named "OuterVariablesButton" and add this code to the foot of the form's constructor:

int clickCount = 1;

OuterVariablesButton.Click += delegate(object sender, System.EventArgs e)
{
    MessageBox.Show("Click " + clickCount.ToString());
    clickCount++;
};

In the above sample, a variable named "clickCount" is declared and initialised outside of the anonymous method. As the anonymous method uses the counter, a reference to the variable is captured and held as an outer variable. As a result, this counter remains in scope to the anonymous method, even after the constructor has completed. Each time the button is clicked, the counter value is outputted and incremented.

Limitations

There are some limitations to the use of anonymous methods. The first, and possibly the most important, is that the anonymous nature of the method prevents it from being called directly. This is not usually a problem but in the rare cases where it is necessary to make a direct call, a standard delegate and named method should be used instead.

The goto statement can be used within an anonymous method. It is not possible to use a goto statement to jump from within an anonymous method to a location outside of the code block. Similarly, it is invalid to jump into an anonymous method's code from the containing class member.

Finally, unsafe code is not permitted within an anonymous method.

29 June 2008