Why does the conditional operator (? :) not work when used with two types that inherit from the same base type?
The conditional expression type must be either the type of the second operand or the type of the third operand according to the language specification. The compiler does not try to find a common base type or another type to which both operands can be converted. Using an expression does not affect how its type is determined, so the purpose of the variables does not matter here.
As for why the language is defined as follows - it greatly simplifies the definition, implementation, testing and forecasting. This is quite common in language design â maintaining a simple language is generally the best option in the long run, even if it makes it somewhat more inconvenient in some specific situations.
See section 7.14 of the C # 4 specification for more details.
Casting the second or third operand to the type you really want for the conditional expression is a way to fix the problem. Note that another situation that often arises is types with a null value:
// 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;
source share