Difference between Func<> with delegate and lambda expression

Memet Olsen picture Memet Olsen · Sep 4, 2012 · Viewed 17.6k times · Source

while deepening myself to more advanced features of C#, I came across some code, which I didn't exactly know the difference of. It's about these two lines:

Func<string, int> giveLength = (text => text.Length);

and

Func<string, int> giveLength = delegate(string text) { return text.Length; };

This can be used in the same way:

Console.WriteLine(giveLength("A random string."));

So basically.. What is the difference of these two lines? And are these lines compiling to the same CIL?

Answer

Jon Skeet picture Jon Skeet · Sep 4, 2012

They're the same, basically. They're both anonymous functions in C# specification terminology.

Lambda expressions are generally more concise, and can also be converted to expression trees, which are crucial for out-of-process LINQ.

Anonymous methods allow you to drop the parameter list if you don't care. For example:

EventHandler handler = delegate { 
    Console.WriteLine("Sender and args don't matter");
};

Given how rarely the latter point is required, anonymous methods are becoming an endangered species in modern C#. Lambda expressions are much more common.