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);
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 have a number of shortcuts to make them more concise:
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"); };
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With