Search code examples
c#syntaxlambdaanonymous-methods

What is the recommended way of writing anonymous functions in C#?


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?


Solution

  • 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