Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the symbol "=>" doing after my method in this C# code?

Tags:

c#

c#-3.0

I recently asked a question here, and someone provided this answer:

private void button1_Click(object sender, EventArgs e)
{
     var client = new WebClient();
     Uri X = new Uri("http://www.google.com");

     client.DownloadStringCompleted += (s, args) => //THIS, WHAT IS IT DOING?
     {
         if (args.Error == null && !args.Cancelled)
         {
             MessageBox.Show();
         }
     };

     client.DownloadStringAsync(X);
}

What is that => doing? It's the first time I'm seeing this.

like image 376
Sergio Tapia Avatar asked Oct 28 '09 23:10

Sergio Tapia


2 Answers

That is the lambda operator. You define an anonymous function which takes two arguments (s, args) (type specifiers omitted), and the body of said function is what appears after the => symbol.

It is conceptually the same as this:

...
client.DownloadStringCompleted += Foo;
}

void Foo(object sender, EventArgs args)
{
    if (args.Error == null && !args.Cancelled)
    {
        MessageBox.Show();
    }
};
like image 173
Ed S. Avatar answered Oct 12 '22 05:10

Ed S.


Basically it says "I am giving you this (s,b)" and you are returning me s*b or something and if you are using lambda with expressions, but it can be something like this : I am giving you this (s,b) and do something with them in the statement block like :

{
  int k = a+b;
  k = Math.Blah(k);
  return k;
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A Lambda expression is an unnamed method written in place of a delegate instance. The compiler immediately converts the lambda expression to either :

  • A delegate instance
  • An expression Tree

delegate int Transformer(int i);

class Test{
  static void Main(){
     Transformer square = x => x*x;
     Console.WriteLine(square(3));
  } 

}

We could rewrite it like this :

delegate int Transformer(int i);

class Test{
  static void Main(){
     Transformer square = Square;
     Console.WriteLine(square(3));
  } 
  static int Square (int x) {return x*x;}
}

A lambda expression has the following form :

(parameters) => expression or statement-block

In previous example there was a single parameter,x, and the expression is x*x

in our example, x corresponds to parameter i, and the expression x*x corresponds to the return type int, therefore being compatible with Transformer delegate;

delegate int Transformer ( int i);

A lambda expression's code can be a statement block instead of an expression. We can rewrite our example as follows :

x => {return x*x;}

An expression tree, of type Expression<T>, representing the code inside the lamda expression in a traversable object model. This allows the lambda expression to be intrepreted later at runtime (Please check the "Query Expression" for LINQ)

like image 45
Tarik Avatar answered Oct 12 '22 05:10

Tarik