Anonymous Methods
Anonymous methods are a C# 2.0 feature that has been mostly 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)); // 9The 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 it. 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.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access