Why Ternary Operator Doesnt Support Nullable Types

added by jebarson007
11/23/2011 1:28:08 AM

1 Kicks, 82 Views

Nullable types and ternary operators are around for many years now and may be not everybody know that ternary operator doesn't support assigning null values to nullable types.


5 comments

dpeterson
11/23/2011 8:42:23 AM
The article is called "Why Ternary Operator Doesnt Support Nullable Types", but you never actually tell us why nullable types aren't supported, just that it's "by design".

jebarson007
11/23/2011 8:52:19 AM
I have mentioned the reason that its because the types are not implicitly convertible. if you read my article i have mentioned that because you cant convert a null to double or vice versa. The operator expects both the value (in true and false part) to be the same type or convertible types

dpeterson
11/23/2011 9:09:06 AM
Yes, that's the error the compiler throws. But that doesn't explain what design decision drove the team at MS to throw that error when attempting to assign null using a ternary operator, even though the type being assigned to is nullable. You could just as easily be using object types instead of reference types and your example of double->null.

It's not a personal attack, I'm just pointing out that beyond talking about the compiler error, and that the team made a design decision to disallow it, you didn't go into the reasons why the decision was made.

jebarson007
11/23/2011 9:52:46 AM
Yes I do understand your question here. May be I should have explained more on the later part of my article.

So if you can understand, the ternary operators where available before the nullable types. So when the ternary operator was designed, it was designed to accept the values (on true and false) to implicitly convertible values. So now the team is however considering to support the same in the future version.

No offense taken :)

vijayst
11/27/2011 4:11:33 AM
Interesting limitation that I was not aware of. I usually use something like this: double? num = true ? (double?)100 : null;

threenine39
12/12/2011 4:21:03 AM
Poosibly and interesting debate here! Some would argue that Ternary Ornary operators are the devils work though. I personally like them.

From a maintenance and debugging view I would prefer to see the more explicit definition provided in the work around. However I do know some people who would much rather see an explicit If.. Then statements.