Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is += (o, arg) => actually achieving?

Tags:

c#

Sorry to ask all, but I'm an old hand Vb.net guy who's transferring to c#. I have the following piece of code that seems to activate when the (in this case) postAsync method is fired. I just don;t understand what the code is doing (as follows):-

app.PostCompleted +=
    (o, args) =>
    {
        if (args.Error == null)
        {
            MessageBox.Show("Picture posted to wall successfully.");
        }
        else
        {
            MessageBox.Show(args.Error.Message);
        }
    };

if anyone could explain what the += (o,args) => is actually acheiving I'd be so greatful....

many thanks in advance. Tim

like image 696
Tim Windsor Avatar asked Jul 26 '11 18:07

Tim Windsor


Video Answer


2 Answers

(o,args) => defines a lambda expression that takes two parameters named o and args. The types of those parameters is inferred according to the type of PostCompleted (if PostCompleted is an EventHandler, then they will be respectively of type Object and EventArgs). The expression's body then follows after the =>.

The result is than added as an handler to PostCompleted.

As such, it's a less verbose way to write:

app.PostCompleted += delegate(object o, EventArgs args)
{
    // ...
};

Which is a shorthand for:

void YourHandler(object o, EventArgs args)
{
    // ...
}

// ...

app.PostCompleted += YourHandler;
like image 54
Etienne de Martel Avatar answered Oct 07 '22 12:10

Etienne de Martel


That is an added handler for the PostCompleted event using a lambda expression. It is similar to

  app.PostCompleted += MyHandler;

  // ...

  private void MyHandler(object sender, EventArgs e) {
      // ...
  }

But when using lambda expressions, you can't detach the handler easily.

like image 28
CodeNaked Avatar answered Oct 07 '22 12:10

CodeNaked