Issue
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?
Solution
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:
- What's the difference between anonymous methods (C# 2.0) and lambda expressions (C# 3.0)
- What is a Lambda?
- C# Lambda expression, why should I use this?
(And indeed many similar questions - try the lambda and lambda-expressions tags.)
Answered By - Jon Skeet Answer Checked By - Cary Denson (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.