What does the ‘=>’ syntax in C# mean?

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.)

Leave a Comment