Lambda Expressions - CSharp Custom Type

CSharp examples for Custom Type:Lambda

Introduction

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

The compiler immediately converts the lambda expression to either:

Given the following delegate type:

delegate int Transformer (int i);

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

Transformer 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 and only if there is exactly one parameter of an inferable type.

In our example, there is a single parameter, x, and the expression is x * x:

x => x * x;

Each parameter of the lambda expression corresponds to a delegate parameter, and the type of the expression (which may be void) corresponds to the return type of the delegate.

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

x => { return x * x; };

Lambda expressions are used most commonly with the Func and Action delegates, so you will most often see our earlier expression written as follows:

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");   // total is 10;

Related Tutorials