11

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?

Memet Olsen
  • 4,578
  • 5
  • 40
  • 50

2 Answers2

19

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks Jon. Btw I recently started reading your ebook 'C# in Depth'. Very helpful! – Memet Olsen Sep 04 '12 at 16:07
  • 3
    @memetolsen: The downside is, if you read enough of my answers here, you'll have read most of the content of the book ;) – Jon Skeet Sep 04 '12 at 16:08
  • 2
    I think 1/3 of my upvotes are on your answers. But still, I'd rather read the book in my spare time instead of reading 22,284 answers :) – Memet Olsen Sep 04 '12 at 16:11
  • @memetolsen: Yes, it's definitely better organized :) – Jon Skeet Sep 04 '12 at 16:13
  • I don't suppose the IL for the anonymous EventHandler example is different whether you include or omit the parameter list, is it? If there's no difference in IL, the lambda might still be preferred as saving keystrokes: `delegate{X("");}` vs `(s,a)=>X("")` – phoog Sep 04 '12 at 16:20
6

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

There's just two different ways to write the same thing. The lambda syntax is newer and more concise, but they do the same thing (in this case).

Note that lambdas (=> syntax) can also be used to form Expression Lambdas, where you make an Expression Tree instead of a delegate. This is nice since you can use the same syntax whether you're using LINQ to Objects (which is based around delegates like Func<T, TResult>) or LINQ to Entities (which uses IQueryable<T> and expression trees).

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373