CSharp - Delegate Anonymous Methods

Introduction

Anonymous methods are like lambda expression.

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 ConverterFunction (int i);

We could write and call an anonymous method as follows:

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

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

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

Or simply:

ConverterFunction sqr = x  => x * x;

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

You can omit the parameter declaration entirely-even if the delegate expects it.

The following creates an empty function:

Action a = delegate { };

The following is also legal:
Action a = delegate { Console.WriteLine ("clicked"); };