Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the '=>' syntax in C# mean?

Tags:

syntax

c#

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?

like image 621
Wolf5 Avatar asked Nov 14 '08 13:11

Wolf5


People also ask

What Is syntax in programming example?

Syntax refers to the rules that define the structure of a language. Syntax in computer programming means the rules that control the structure of the symbols, punctuation, and words of a programming language. Without syntax, the meaning or semantics of a language is nearly impossible to understand.

What is syntax error in C?

Syntax errors are mistakes in the source code, such as spelling and punctuation errors, incorrect labels, and so on, which cause an error message to be generated by the compiler.

What is the syntax of main function in C?

int main (int argc, char *argv) A main() function can be called using command line arguments. It is a function that contains two parameters, integer (int argc) and character (char *argv) data type. The argc parameter stands for argument count, and argv stands for argument values.


1 Answers

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

like image 66
Jon Skeet Avatar answered Oct 05 '22 11:10

Jon Skeet