Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is '=>'? (C# Grammar Question) [duplicate]

Tags:

c#

.net

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);
like image 916
Yeonho Avatar asked Apr 28 '10 07:04

Yeonho


2 Answers

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"); };
    
like image 64
Jon Skeet Avatar answered Oct 01 '22 21:10

Jon Skeet


Lambda operator:

A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls...

Huzzah!

like image 42
Strelok Avatar answered Oct 01 '22 22:10

Strelok