tags:

views:

893

answers:

4

Duplicate: http://stackoverflow.com/questions/299703/c-delegate-keyword-vs-lambda-notation

I understand the anonymous methods can be used to define delegates and write inline functions. Is using Lambda expressions any different from this?

I guess I am a little confused on when to use what.

Edit: Also, appears that to use either anonymous or lambdas, there needs to be an Extension method for the type?

+3  A: 

Not really no. They are essentially the exact same feature with different syntax constructs. The general shift appears to be away from the C# 2.0 anonymous method syntax towards the lambda style syntax for both anonymous expressions and functions though.

JaredPar
+11  A: 

A lambda expression is simply shortcut syntax for an anonymous method. Anonymous methods look like this:

delegate(params) {method body}

The equivalent lambda expression would look like this:

params => method body

In short, all lambda expressions are anonymous methods, but it is possible to have an anonymous method that is not written in lambda syntax (like the first example above). Hope this is helpful!

Adam Alexander
+1, but aren't lambda expressions just reinventing the wheel (rather poorly, as I though anonymous methods made more sense).
SnOrfus
so lambada expression can NOT have return valuess? while anonymous method can?
SnOrfus: yes they do the same thing so you're right, it's just a matter of syntax preference. Sasha: both lambdas and anonymous methods can have return values.
Adam Alexander
Lambdas make the use of anonymous delegates much more terse through syntax shortcuts and type inference.i = l.Count(delegate(string x) { return x.Length == 2; });i = l.Count(x => x.Length == 2);
Mark
lambdas use implied typing, so "(x, y) => x + y;" is much more concise than "delegate(int x, int y) { return x + y; }" Use lambdas when they promote readability, and anonymous delegates when they make sense.
Michael Meadows
+1  A: 

Here's a good explanation: C#: delegate keyword vs. lambda notation

chris
+1  A: 

Lambda expressions can be converted to expression trees, while anonymous delegates cannot.

bdukes