C# Lambda Expressions

In this chapter you will learn:

  1. What are C# Lambda Expressions
  2. How to create Lambda Expressions
  3. Example for Lambda Expressions
  4. Note for Lambda Expressions
  5. Lambda and Func and Action delegates
  6. Explicitly Specifying Lambda Parameter Types

Description

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

Syntax

A lambda expression has the following form:

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

Example

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

Note

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.

Lambda and Func and Action delegates

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;

Explicitly Specifying Lambda Parameter Types

The compiler can usually infer the type of lambda parameters contextually. Consider the following expression:


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

The compiler uses type inference to infer that x is an int.

We could explicitly specify x's type as follows:


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

Next chapter...

What you will learn in the next chapter:

  1. How to use Func, Action and lambda
  2. Example for lambda expression from Func, Action
Home »
  C# Tutorial »
    C# Types »
      C# Lambda
C# Lambda Expressions
Func, Action and lambda
C# Lambda Capturing Outer Variables