1
var seq = Enumerable.Range(1, 10).Reverse();
var sort1 = seq.OrderBy(i => i);
var sort2 = seq.OrderBy(delegate(int i) { return i; });

i think sort2 is more explicit but sort 1 is shorter. besides that, i don't really know the difference. what is the recommended way of doing this?

usr
  • 168,620
  • 35
  • 240
  • 369
  • possible duplicate of [What's the difference between anonymous methods (C# 2.0) and lambda expressions (C# 3.0)?](http://stackoverflow.com/questions/208381/whats-the-difference-between-anonymous-methods-c-2-0-and-lambda-expressions) – nawfal Jul 06 '14 at 20:05

7 Answers7

12

Lambda expressions are (IMO) better than anonymous methods in every case except where you don't care about the parameters, in which case there's a nice shortcut:

// Lambda expression has to specify parameter types
EventHandler x = (sender, args) => Console.WriteLine("Hi");

// Anonymous method can ignore them
EventHandler x = delegate { Console.WriteLine("Hi"); };

Lambda expressions have two other "problems" IMO:

  • Obviously they're not available if you're not using C# 3. (Although you can target .NET 2.0 from VS2008 and still use them.)
  • The syntax for a parameterless lambda expresssion is somewhat clunky:

    () => stuff
    
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • is it a MUST that lambda has to specify parameter types? EventHandler x = () => Console.WriteLine("Hi"); – Rony Jun 24 '09 at 19:01
  • 1
    That's explicitly specifying an empty list of parameters - which means it isn't convertible to EventHandler. – Jon Skeet Jun 24 '09 at 19:02
  • Isn't ()=>stuff going to be _ => stuff in C#4? – Jeff Yates Jun 24 '09 at 19:02
  • @Jeff: Not that I've seen. Don't forget that _ is a valid identifier. I've heard nothing about this, and it doesn't work in beta 1. – Jon Skeet Jun 24 '09 at 19:04
  • @Jon: I wasn't sure. I had seen it in a blog somewhere from inside Microsoft. I'll hunt it down - I forgot to follow up on it and find out what it was. Now seems as good a time as any. – Jeff Yates Jun 24 '09 at 19:05
  • 3
    It's worth mentioning that aside from their concise syntax, Lambdas have one significant advantage over delegates, in that they can be processed by the compiler into either a delegate or an expression tree as needed. A feature that makes it possible to programmatically manipulate the expressions passed in as lambdas. – LBushkin Jun 24 '09 at 19:07
  • 1
    @JonSkeet why is `() => stuff` clunky? Isn't `delegate { return stuff; }` clunkier? – nawfal Jul 06 '14 at 20:05
2

I much prefer the lambda syntax (sort1) where possible. I only use the more verbose syntaxes where they are required. I consider the extra stuff non-productive code that just gets in the way of understanding what I'm writing.

Edit: Unless of course I'm working on a .NET 2.0 app, where you can't use the lambda syntax. Then, I'm just glad I at least have anonymous methods.

Jonathan Rupp
  • 15,522
  • 5
  • 45
  • 61
  • 2
    You can use lambdas for .NET 2.0 projects so long as you're using VS2008 and targeting .NET 2.0. It's worth distinguishing between language version and framework version. – Jon Skeet Jun 24 '09 at 19:03
2

I find this depends on the scenario as the important aspect is making sure the intent of your code is well documented for future maintainers. Therefore, sometimes a lambda works best, but other times an anonymous method is a better option. The problem with lambdas where more than argument is needed, is that the syntax starts to look cluttered, so it can sometimes be useful to use the anonymous method delegate syntax to provide a more recognisable structure.

In the example you have given, the lambda is the better option as it is clear and concise; however, when declaring say an inline event handler, an anonymous method might provide a better solution (with regards to maintainability).

Jeff Yates
  • 61,417
  • 20
  • 137
  • 189
  • 1
    When you say "other times a delegate is a better option" I think you mean "other times an anonymous method is a better option". In this case, both expressions are being converted to delegates. – Jon Skeet Jun 24 '09 at 19:02
  • @Jon: yes - I was tripping over my words. :) – Jeff Yates Jun 24 '09 at 19:03
  • Don't worry about it too much - I'm just a massive terminology pedant :) (That doesn't mean I always get it right, of course!) – Jon Skeet Jun 24 '09 at 19:07
  • @Jon: I get called a pedant more than you could imagine - being British surrounded by these Americans, language becomes an issue. – Jeff Yates Jun 24 '09 at 19:12
1

There are few (and I can only think of one off the top) where I like the delegate syntax over the lambda expression ...

public event Action Evt = delegate {};
public event Action Evt = () => { };

... for example. The rest of the time, delegate just gets in the way. Per Jon's comment ...

public event EventHandler Evt = delegate {};
public event EventHandler Evt = (s,ea) => { };
JP Alioto
  • 44,864
  • 6
  • 88
  • 112
  • Actually that's a bad example of the event bit, because Action doesn't take any parameters - the lambda expression is fine here. Change it to EventHandler and the lambda expression becomes ugly because you have to give names to the parameters even if you're not using them. – Jon Skeet Jun 24 '09 at 19:06
0

As far as I know both approaches will generate the exact same IL code (at least in this example), so it's really a matter of taste. I often think lambda tastes nicer.

Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
0

sort1 - Lambdas I think is the prefered way to write Anonymous methods

Rony
  • 9,331
  • 2
  • 22
  • 22
  • 1
    Just to be a massive pedant (and hey, I'm commenting on all the other answers :) an anonymous method is by definition the syntax seen in sort2. Both lambda expressions and anonymous methods count as anonymous functions; both can be converted to delegate types; only lambda expressions can be converted to expression trees. – Jon Skeet Jun 24 '09 at 19:07
0

I prefer lambda-expressions since they offer the the most concise syntax and resemble the lambdas in functional programming languages where this construct originally comes from. When the expression contains more than one statement or unfunctional constructs, I'll use delegate. Parameterless, multi-lined or explicitly typed lambda expressions may look somewhat weird and hence lose their major advantage (being more readable).

g = (x => 2 * f(x) + 1); // Nice functional one-liner

// but

action = delegate (int arg) {
    SendSystemMessage(arg);
    Console.WriteLine("Got value: {0}", arg);
};
Dario
  • 48,658
  • 8
  • 97
  • 130