=> operator (C# reference)

The => token is supported in two forms: as the lambda operator and as a separator of a member name and the member implementation in an expression body definition.

Lambda operator

In lambda expressions, the lambda operator => separates the input variables on the left side from the lambda body on the right side.

The following example uses the LINQ feature with method syntax to demonstrate the usage of lambda expressions:

string[] words = { "bot", "apple", "apricot" };
int minimalLength = words
  .Where(w => w.StartsWith("a"))
  .Min(w => w.Length);
Console.WriteLine(minimalLength);   // output: 5

int[] numbers = { 1, 4, 7, 10 };
int product = numbers.Aggregate(1, (interim, next) => interim * next);
Console.WriteLine(product);   // output: 280

Input variables of lambda expressions are strongly typed at compile time. When the compiler can infer the types of input variables, like in the preceding example, you may omit type declarations. If you need to specify the type of input variables, you must do that for each variable, as the following example shows:

int[] numbers = { 1, 4, 7, 10 };
int product = numbers.Aggregate(1, (int interim, int next) => interim * next);
Console.WriteLine(product);   // output: 280

The following example shows how to define a lambda expression without input variables:

Func<string> greet = () => "Hello, World!";
Console.WriteLine(greet());

For more information, see Lambda expressions.

Expression body definition

An expression body definition has the following general syntax:

member => expression;

where expression is a valid expression. The return type of expression must be implicitly convertible to the member's return type. If the member's return type is void or if the member is a constructor, a finalizer, or a property set accessor, expression must be a statement expression; it can be of any type then.

The following example shows an expression body definition for a Person.ToString method:

public override string ToString() => $"{fname} {lname}".Trim();

It's a shorthand version of the following method definition:

public override string ToString()
{
   return $"{fname} {lname}".Trim();
}

Expression body definitions for methods and read-only properties are supported starting with C# 6. Expression body definitions for constructors, finalizers, property accessors, and indexers are supported starting with C# 7.0.

For more information, see Expression-bodied members.

Operator overloadability

The => operator cannot be overloaded.

C# language specification

For more information, see the Anonymous function expressions section of the C# language specification.

See also