When to use or not lambda expressions

I see that lambda expressions have become a very useful tool at some points in the language. I use them a lot, and most of the time they fit very nicely and make the code shorter and perhaps more clear.

Now .. I have seen some, I would say, overuse of them. Some people like them so much that they try to use them wherever they can. Sometimes C # code looks like a functional language.

Other factors are the costs associated with lambda reflection, and which are not debug friendly.

I would like to hear opinions on how well and how clearly the code is to use more or less lambda expressions.

(this is not a good example, but let it be a trigger)

I wrote the following code. Using delegate { return null; } 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 wise resharper (even if he literally eats memory several times) made me the following suggestion

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

From my point of view, the code using the delegate looks more understandable. I am not opposed to expressing Lamdba, I just would like to hear some tips on how and when to use them.

+4
source share
1 answer

There are a few questions here.

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

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

As for the use of lambda expressions in the whole code - Personally, I am a pretty heavy user of them. I find that they often make life a lot easier than defining many methods. If part of the code is not reused by any other methods (it will be called and exist in only one place), I will use lambda to express it.

If a piece of code will be used more than once, it should be pulled into the (non-anonymous) method. In addition, if a piece of code is something that can and should be tested, I try to make a method for it, because it simplifies testability.

+7
source

All Articles