No need for a lambda!

Chapter 9: Lambda expressions and expression trees: 9.2.1

Created: 5/13/2008
Last updated: 5/13/2008

The code in listing 9.4 can be abbreviated even further than just removing the braces from round the body of the lambda expression. We don't need a lambda expression at all - we can use a simple method group conversion, converting this:

Action<Film> print = film => Console.WriteLine(film);

to this:

Action<Film> print = Console.WriteLine;

Of course as it's now so brief, we're not getting as much benefit from the extra variable. We can eliminate it completely, leaving this as the rest of the listing:

It's a judgement call as to which form is most readable - I quite like keeping the extra variable - but it's worth taking note of this. When you write a "simple" lambda expression, just think that it might not need to be a lambda at all. I'll readily admit this possibility had completely passed me by in this case - thanks are due to Joe Albahari for pointing it out.