Use and explanation of syntax =>

I saw a lot of C # code samples with => syntax.

Can anyone explain what the syntax is?

 select x => x.ID 
+7
c #
source share
3 answers

can anyone explain what syntax is used =>

The bold arrow syntax is used to create something called Lambda Expression in C #. It is just syntactic sugar for creating delegates.

The output expression does not make any sense, but you can see that it is used in LINQ:

 var strings = new[] { "hello", "world" }; strings.Where(x => x.Contains("h")); 

The syntax x => x.Contains("h") will be output by the compiler as Func<string, bool> , which will be generated at compile time.


Edit:

If you really want to see what happens behind the scenes, you can take a look at the decompiled code inside any .NET decompiler:

 [CompilerGenerated] private static Func<string, bool> CS$<>9__CachedAnonymousMethodDelegate1; private static void Main(string[] args) { string[] strings = new string[] { "hello", "world" }; IEnumerable<string> arg_3A_0 = strings; if (Program.CS$<>9__CachedAnonymousMethodDelegate1 == null) { Program.CS$<>9__CachedAnonymousMethodDelegate1 = new Func<string, bool> (Program.<Main>b__0); } arg_3A_0.Where(Program.CS$<>9__CachedAnonymousMethodDelegate1); } [CompilerGenerated] private static bool <Main>b__0(string x) { return x.Contains("h"); } 

Here you can see that the compiler created a cached delegate of type Func<string, bool> called Program.CS$<>9__CachedAnonymousMethodDelegate1 and a named method called <Main>b__0 , which is passed to the Where clause.

+11
source share

This syntax is used for lambda expressions - https://msdn.microsoft.com/en-us/library/bb397687.aspx

 delegate int del(int i); static void Main(string[] args) { var myDelegateLambda = x => x * x; // lambda expression Func<int, int> myDelegateMethod = noLambda; // same as mydelegate, but without lambda expression int j = myDelegateLambda(5); //j = 25 } private int noLambda(int x) { return x * x; } 

As you can see, the lambda expression is very useful for passing simple delegates.

+4
source share

This is the syntax used for lambda expresssion .

Below the syntax, select an x object and get the x.ID value from it.

 select x => x.ID 
0
source share

All Articles