Anonymous Methods

Anonymous methods are a C# 2.0 feature that has been largely subsumed by lambda expressions. An anonymous method is like a lambda expression, except that it lacks implicitly typed parameters, expression syntax (an anonymous method must always be a statement block), and the ability to compile to an expression tree.

To write an anonymous method, you include the delegate keyword followed (optionally) by a parameter declaration and then a method body. For example, given this delegate:

delegate int Transformer (int i);

we could write and call an anonymous method as follows:

Transformer sqr = delegate (int x) {return x * x;};
Console.WriteLine (sqr(3));         // 9

The first line is semantically equivalent to the following lambda expression:

Transformer sqr =       (int x) => {return x * x;};

Or simply:

Transformer sqr =            x  => x * x;

A unique feature of anonymous methods is that you can omit the parameter declaration entirely—even if the delegate expects them. This can be useful in declaring events with a default empty handler:

public event EventHandler Clicked = delegate { };

This avoids the need for a null check before firing the event. The following is also legal (notice the lack of parameters):

Clicked += delegate { Console.Write ("clicked"); };

Anonymous methods capture outer variables in the same way lambda expressions do.

Get C# 4.0 Pocket Reference, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.