tags:

views:

297

answers:

4

I was watching a Silverlight tutorial video, and I came across an unfamiliar expression in the example code.

what is => ? what is its name? could you please provide me a link? I couldn't search for it because they are special characters.

code:

        var ctx = new EventManagerDomainContext();
        ctx.Events.Add(newEvent);
        ctx.SubmitChanges((op) =>
        {
            if (!op.HasError)
            {
                NavigateToEditEvent(newEvent.EventID);
            }
        }, null);
+12  A: 

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

Huzzah!

Strelok
Lambda always makes me think of lisp, the first language I learned with lambda expressions.
Patrick
@Patrick because Lisp is heavily based on the lambda calculus http://en.wikipedia.org/wiki/Lambda_calculus , which is also where the name of this operator comes from
AakashM
+12  A: 

It's a lambda expression.

If you're familiar with anonymous methods from C# 2, lambda expressions are mostly similar but more concise. So the code you've got could be written like this with an anonymous method:

var ctx = new EventManagerDomainContext();
ctx.Events.Add(newEvent);
ctx.SubmitChanges(delegate(Operation op)
{
    if (!op.HasError)
    {
        NavigateToEditEvent(newEvent.EventID);
    }
}, null);

Aspects of anonymous methods such as the behaviour of captured variables work the same way for lambda expressions. Lambda expressions and anonymous methods are collectively called anonymous functions.

There are a few differences, however:

  • Lambda expressions can be converted into expression trees as well as delegates.
  • Lambda expressions have a number of shortcuts to make them more concise:

    • If the compiler can infer the parameter types, you don't need to specify them
    • If the body is a single statement, you don't need to put it in braces and you can omit the "return" part of a return statement
    • If you have a single parameter with an inferred type, you can miss out the brackets

    Putting these together, you get things like:

    IEnumerable<string> names = people.Select(person => person.Name);
    
  • Lambda expressions don't support the "I don't care how many parameters there are" form of anonymous methods, e.g.

    EventHandler x = delegate { Console.WriteLine("I was called"); };
    
Jon Skeet
+1  A: 

It's a C# lambda expression. You can read all about them here.

Seventh Element
+1  A: 

I couldn't search for it because they are special characters.

Sometimes the old-fashioned ways are the best. This worked for me:

  • Start Visual Studio 2008 or later
  • Hit F1
  • Once the Help Document Explorer has come up, ensure the Index tab is selected in the left hand pane
  • Enter => in the Look for field
  • The first item in the list is now the help article you need.
AakashM
Oh snap! :-) But really, sometimes I think people macroes their F1 key to open SO instead
Patrick