views:

212

answers:

1

I see lambda expressions have become a very useful tool at some points in the language. I've been using them a lot and most of the time they fit really nice and make the code shorter and perhaps clearer.

Now.. I've seen some , I would say excessive use of them. Some people like them so much that try to use them everywhere they can.. Some times the C# code looks like a functional language.

Other factors against are the cost using reflection by lambda and that not friendly to debugging.

I would like to hear opinions about how good and how code clear it is to use more or less the lambda expressions.

(this is not the better example, but let's say it was the trigger)

I was writing the following code. The use of the delegate { return null; } helps me avoid having to ask if the event is null or not every time I have to use it.

public delegate ContactCellInfo.Guest AddGuest();
public event AddGuest GuestRequest = delegate { return null;}

Im using resharper and the wise resharper( even it some times literaly eats the memory) made me the following suggestion

public delegate ContactCellInfo.Guest AddGuest();
public event AddGuest GuestRequest = () => null;

At my point of view the code using the delegate looks clearer. I am not against the Lamdba expression just would like to hear some advices on how and when to use them.

+5  A: 

There are somewhat two questions here.

First, as for your example, using a lambda vs. using the anonymous delegate syntax. The generated code by the compiler will be identical, so it does not come down to a performance difference, but rather a readability difference.

Personally, I find the lambda syntax easy to follow. I find that the lambda syntax is almost always cleaner, more concise, and more understandable than the anonymous delegate syntax, so I prefer it nearly always.

As for using lambda expressions throughout the code - Personally, I am a fairly heavy user of them. I find that they often make life much easier than having lots of methods defined. If a piece of code is not going to be reused by any other methods (it will only be called and exist in one place), I will use a lambda to express it.

If a piece of code is going to be used more than once, it should be pulled out into a (non-anonymous) method. Also, if a piece of code is something that could and should be tested, I tend to make a method for it, since that eases testability.

Reed Copsey