3

Possible Duplicate:
C# Lambda ( => )

For instance

Messenger.Default.Register<AboutToCloseMessage>(this, (msg) =>
        {
            if (msg.TheContainer == this.MyContainer) // only care if my container.
            {
                // decide whether or not we should cancel the Close
                if (!(this.MyContainer.CanIClose))
                {
                    msg.Execute(true); // indicate Cancel status via msg callback.
                }
            }
        });
Community
  • 1
  • 1
Rdeluca
  • 51
  • 2

5 Answers5

2

The

=>
Operator is used for Lambda Expressions.

http://msdn.microsoft.com/en-us/library/bb397687.aspx

It allows you to define an anonymous function "on the fly" and can be used to create delegates or expression tree types.

invalidsyntax
  • 640
  • 1
  • 5
  • 14
1

It is a lambda, it allows you to create a function easily.

in your example you can also write:

Messenger.Default.Register<AboutToCloseMessage>(this, delegate(Message msg)
{
    if (msg.TheContainer == this.MyContainer) // only care if my container.
    {
        // decide whether or not we should cancel the Close
        if (!(this.MyContainer.CanIClose))
        {
            msg.Execute(true); // indicate Cancel status via msg callback.
        }
    }
});

or even

Messenger.Default.Register<AboutToCloseMessage>(this, foobar);

// somewhere after //
private void foobar(Message msg)
{
    if (msg.TheContainer == this.MyContainer) // only care if my container.
    {
        // decide whether or not we should cancel the Close
        if (!(this.MyContainer.CanIClose))
        {
            msg.Execute(true); // indicate Cancel status via msg callback.
        }
    }
}
Baptiste Pernet
  • 3,318
  • 22
  • 47
0

It's a lambda expression (http://msdn.microsoft.com/en-us/library/bb397687.aspx).

Achim
  • 15,415
  • 15
  • 80
  • 144
0

its a lamda expression (Function Argument ) => { Function Body}

The type of the argument can be specified but the complier will generally just interpret it.

rerun
  • 25,014
  • 6
  • 48
  • 78
0

That is how you define lambda in C#. msg is the argument, passed to the lambda method, and the rest is the body of the method.

The equivalent of that is this:

Messenger.Default.Register<AboutToCloseMessage>(this, SomeMethod);

void SomeMethod(SomeType msg)
{
    if (msg.TheContainer == this.MyContainer) // only care if my container.
    {
        // decide whether or not we should cancel the Close
        if (!(this.MyContainer.CanIClose))
        {
             msg.Execute(true); // indicate Cancel status via msg callback.
        }
    }
}
Nawaz
  • 353,942
  • 115
  • 666
  • 851