views:

225

answers:

5
+10  Q: 

What is this event?

Could someone explain what this C# code is doing?

// launch the camera capture when the user touch the screen
this.MouseLeftButtonUp += (s, e) => new CameraCaptureTask().Show();

// this static event is raised when a task completes its job
ChooserListener.ChooserCompleted += (s, e) =>
{
    //some code here
};

I know that CameraCaptureTask is a class and has a public method Show(). What kind of event is this? what is (s, e)?

+9  A: 
(s, e) => new CameraCaptureTask().Show();

This is an anonymous delegate (lambda expression). This takes 2 parameters (s and e (which are unused)), and then create a new CameraCaptureTask and show it.

KennyTM
+1  A: 
(s, e) => { }

is a lambda expression. In this case, it's just a quick way of defining a method (an inline method) without having to create a separate method in the class.

Matti Virkkunen
+1  A: 

Lambda notation, s stands for sender, e for eventargs, the event's arguments.

luvieere
A: 

As mentioned, the syntax you are seeing is a lambda expression. The code you have in a simplistic view is a short hand for the following

this.MouseLeftButtonUp += Handle_MouseLeftButtonUp;

void Handle_MouseLeftButtonUp(object s, MouseButtonEventArgs e)
{
  new CameraCaptureTask().Show(); 
}

Check the references others have given, Lambda expression provide far more.

Chris Taylor
+8  A: 

When attaching event handlers, you can do in three different ways:

The old fashioned verbose way:

this.MouseLeftButtonUp += Handle_MouseLeftButtonUp;
void Handle_MouseLeftButtonUp(object s, MouseButtonEventArgs e)
{
  new CameraCaptureTask().Show(); 
}

An anonymous method:

this.MouseLeftButtonUp += delegate(object s, MouseButtonEventArgs e) {
  new CameraCaptureTask().Show(); 
}

Or, using a lambda expression:

this.MouseLeftButtonUp += (s, e) => new CameraCaptureTask().Show(); 

Imagine the last one as a 'compact form' of the one using the delegate. You could also use Parentheses:

this.MouseLeftButtonUp += (s, e) => {
  new CameraCaptureTask().Show(); 
}
Fernando