⇒ Lambda operator

suggest change

The => operator has the same precedence as the assignment operator = and is right-associative.

It is used to declare lambda expressions and also it is widely used with LINQ Queries:

string[] words = { "cherry", "apple", "blueberry" };

int shortestWordLength = words.Min((string w) => w.Length); //5

When used in LINQ extensions or queries the type of the objects can usually be skipped as it is inferred by the compiler:

int shortestWordLength = words.Min(w => w.Length); //also compiles with the same result

The general form of lambda operator is the following:

(input parameters) => expression

The parameters of the lambda expression are specified before => operator, and the actual expression/statement/block to be executed is to the right of the operator:

// expression
(int x, string s) => s.Length > x // expression
(int x, int y) => x + y // statement
(string x) => Console.WriteLine(x)
// block
(string x) => {
        x += " says Hello!";

This operator can be used to easily define delegates, without writing an explicit method:

delegate void TestDelegate(string s);

TestDelegate myDelegate = s => Console.WriteLine(s + " World");


instead of

void MyMethod(string s)
    Console.WriteLine(s + " World");

delegate void TestDelegate(string s);

TestDelegate myDelegate = MyMethod;


Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents