C# Language Func delegates Lambda & anonymous methods

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any C# Language Question?