C# Language Lambda & anonymous methods


Example

An anonymous method can be assigned wherever a delegate is expected:

Func<int, int> square = delegate (int x) { return x * x; }

Lambda expressions can be used to express the same thing:

Func<int, int> square = x => x * x;

In either case, we can now invoke the method stored inside square like this:

var sq = square.Invoke(2);

Or as a shorthand:

var sq = square(2);

Notice that for the assignment to be type-safe, the parameter types and return type of the anonymous method must match those of the delegate type:

Func<int, int> sum = delegate (int x, int y) { return x + y; } // error
Func<int, int> sum = (x, y) => x + y; // error