11

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

Can anyone explain about what the usage of this syntax?

select x => x.ID
Cœur
  • 37,241
  • 25
  • 195
  • 267
Yu Yenkan
  • 745
  • 1
  • 9
  • 32
  • 2
    [Lambda expressions: Why should I use them?](http://stackoverflow.com/questions/167343/c-sharp-lambda-expressions-why-should-i-use-them) – Soner Gönül May 18 '15 at 08:50

3 Answers3

19

can anyone explain about what the usage of => syntax?

The "fat arrow" syntax is used to form something called a Lambda Expression in C#. It is a mere syntactical sugar for a delegates creation.

The expression you provided doesn't make any sense, but you can see it used alot in LINQ:

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

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


Edit:

If you really want to see whats going on "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");
}

You can see here 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 get passed to the Where clause.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
5

This syntax is used by 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 to convey simple delegates.

Pawel Maga
  • 5,428
  • 3
  • 38
  • 62
3

It is a syntax used for lambda expresssion.

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

select x => x.ID
Abhishek
  • 6,912
  • 14
  • 59
  • 85