tags:

views:

72

answers:

3

It feels strange to me to be casting null to a type so I wanted to double check that this is the right way to do this:

decimal? d = data.isSpecified ? data.Value : (decimal?)null;

alt text

alt text

NOTE: I am marking the answer that suggests the method that I personally like the best:

decimal? d = data.isSpecified ? data.Value : default(decimal?)
+2  A: 

Yes, it is perfectly fine.

klausbyskov
+1  A: 

Is data.Value of type decimal? If so, here's an alternative notation, without the cast:

decimal? d = data.isSpecified ? new decimal?(data.Value) : null;
Tim Robinson
+4  A: 

Yes, that's fine. Alternatives:

condition ? (decimal?) value : null

condition ? new decimal?(value) : null

condition ? value : default(decimal?)

condition ? value : new decimal?()

Pick whichever you find most readable.

There's nothing you can do outside the expression itself, as it's the type of the expression which the compiler doesn't know. For example, putting the whole expression in brackets and casting it wouldn't help.

Jon Skeet
Would it work without the cast if `value` was already `decimal?` ?
Robert Harvey
@Robert: Yes, in that case it would be fine. The problem is that the type of the conditional expression *either* has to be the type of the LHS *or* the type of the RHS... and "null" doesn't have a type.
Jon Skeet