How come the conditional operator (?:
) doesn\'t work when used with two types that inherit from a single base type?
The example I have is:
How come the conditional operator (?:) doesn't work when used with two types that inherit from a single base type?
The type of the conditional expression has to be either the type of the second operand or the type of the third operand, as per the language specification. The compiler doesn't try to find a common base type, or another type that both operands can be converted to. The use of the expression doesn't affect how its type is determined - so the variable assignment is irrelevant here.
As for why the language is defined like this - it makes it considerably simpler to specify, implement, test and predict. This is fairly common in language design - keeping the language simple is usually a better bet in the long run, even if it makes it slightly more awkward in some specific situations.
See section 7.14 of the C# 4 spec for more details.
Casting either the second or third operand to the type that you actually want for the conditional expression is the way to fix the problem. Note that another situation this often comes up in is nullable types:
// Invalid
int? a = SomeCondition ? null : 10;
// All valid
int? a = SomeCondition ? (int?) null : 10;
int? b = SomeCondition ? default(int?) : 10;
int? c = SomeCondition ? null : (int?) 10;