Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to express a parameterless lambda than () =>?

Tags:

c#

lambda

The () seems silly. is there a better way?

For example:

ExternalId.IfNotNullDo(() => ExternalId = ExternalId.Trim());

like image 320
brendanjerwin Avatar asked Jan 08 '09 15:01

brendanjerwin


People also ask

Can we write a Parameterless lambda expression?

No, there isn't. Lambda expressions are optimised (in terms of syntax) for the single parameter case. I know that the C# team feels your pain, and have tried to find an alternative. Whether there ever will be one or not is a different matter.

Can lambda expression have more than one statement?

Yes, you can use multiple lines.

Can we use dynamic in lambda expression?

In 2010, the Dynamic Type was introduced and that gave us the ability to create dynamic lambda expressions.

Can you use ref and out parameters in lambda expression if declared outside?

#1,191 – Lambda Can't Capture ref or out Parameters Lambda expressions can make use of variables declared in a containing scope, i.e. outside of the expression itself. They cannot, however, use variables that are defined as ref or out parameters in an outer scope.


1 Answers

Sort of! There is a new idiom in town, that is nice and may help you in some cases. It is not fully what you want, but sometimes I think you will like it.

Since underscore ("_") is a valid C# identifier, it is becoming a common idiom to use it as a parameter name to a lambda in cases where you plan to ignore the parameter anyway. If other coders are aware of the idiom, they will know immediately that the parameter is irrelevant.

For example:

ExternalId.IfNotNullDo( _ => ExternalId=ExternalId.Trim()); 

Easy to type, conveys your intent, and easier on the eyes as well.

Of course, if you're passing your lambda to something that expects an expression tree, this may not work, because now you're passing a one-parameter lambda instead of a no-parameter lambda.

But for many cases, it is a nice solution.

like image 93
Charlie Flowers Avatar answered Sep 27 '22 18:09

Charlie Flowers