C# – What Does the ‘=>’ Syntax Mean?

c++syntax

I just came over this syntax in some of the questions in this forum, but Google and any other searchengine tends to block out anything but letters and number in the search so it is impossible to search out "=>".

So can anyone tell me what it is and how it is used?

Best Answer

It's the lambda operator.

From C# 3 to C# 5, this was only used for lambda expressions. These are basically a shorter form of the anonymous methods introduced in C# 2, but can also be converted into expression trees.

As an example:

Func<Person, string> nameProjection = p => p.Name;

is equivalent to:

Func<Person, string> nameProjection = delegate (Person p) { return p.Name; };

In both cases you're creating a delegate with a Person parameter, returning that person's name (as a string).

In C# 6 the same syntax is used for expression-bodied members, e.g.

// Expression-bodied property
public int IsValid => name != null && id != -1;

// Expression-bodied method
public int GetHashCode() => id.GetHashCode();

See also:

(And indeed many similar questions - try the lambda and lambda-expressions tags.)

Related Question