tags:

views:

552

answers:

4

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

For example:

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

+2  A: 

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.

Jon Skeet
+5  A: 

For a lambda, no: you need () =>

Is it for a delegate or an expression? For delegates, another option is delegate {...}. This may or may not be desirable, depending on the scenario. It is more keys, certainly...

In some cases (not this one) you can use a target method directly - i.e.

ExternalId.IfNotNullDo(SomeMethod);
Marc Gravell
A: 

Dont know exactly what you're doing but as you are doing:

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

can you not restructure it as:

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

-- that would allow you to e.g. convert your nullable to a direct reference to the wrapped item? or:

ExternalId.IfNotNullReplaceWith(item => item.Trim());
Ruben Bartelink
+5  A: 

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. You can find out more about it here.

Charlie Flowers
I really don't see how this is better than (). Swapping slightly ugly syntax for slightly ugly pseudo-syntax doesn't seem like a win.
Greg Beech
Well, you're definitely welcome to your opinion. It is a subjective matter. But to me it greatly reduces visual clutter, is easier to read, and is easier to type. The original question was motivated by a dislike of the () syntax, so this presents an alternative.
Charlie Flowers
Awesome! This is what I was after. Not Quite as ugly and at least it's an option.
brendanjerwin
In F#, _ is a matchall pattern, so it's nice having similarity when having to use C#. Many of my event handlers look like "foo += (_,__) ...".
MichaelGG