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));         // 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 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.107.193