Anonymous Methods

Anonymous methods are a C# 2.0 feature that has been subsumed by C# 3.0 lambda expressions. An anonymous method is like a lambda expression, but it lacks the following features:

  • Implicitly typed parameters

  • Expression syntax (an anonymous method must always be a statement block)

  • The ability to compile to an expression tree by assigning to Expression<T>

To write an anonymous method, include the delegate keyword, followed 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;

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

Get C# 3.0 Pocket Reference, 2nd 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.