C# Lambda Expressions

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;




















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor