C# Language Operators => Lambda operator

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

3.0

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!";
        Console.WriteLine(x);
    }

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");

myDelegate("Hello");

instead of

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

delegate void TestDelegate(string s);

TestDelegate myDelegate = MyMethod;

myDelegate("Hello");


Got any C# Language Question?