CSharp - Delegate Lambda Expressions


A lambda expression is an unnamed instance method of a delegate.

Given the following delegate type:

delegate int ConverterFunction (int i);

we could assign and invoke the lambda expression x => x * x as follows:

ConverterFunction sqr = x => x * x;
Console.WriteLine (sqr(3));    // 9


A lambda expression has the following form:

(parameters) => expression-or-statement-block

You can omit the parentheses if there is only one inferable type parameter.

x => x * x has a single parameter, x, and the expression is x * x:

A lambda expression's code can be a statement block. We can rewrite our example as follows:

x => { return x * x; };

Lambda expressions can be used with the Func and Action delegates:

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

Here's an example of an expression that accepts two parameters:

Func<string,string,int> totalLength = (s1, s2) => s1.Length + s2.Length;
int total = totalLength ("hello", "world");   

Explicit Lambda Parameter Types

We can fix this by explicitly specify x's type as follows:

Func<int,int> sqr = (int x) => x * x;

Related Topics