0

This code doesn't compile. Am I wrong to expect it to?

interface I{};
class A : I{};
class B : I{};
I mything = someBoolCondition ? new A : new B;

The problem being that the compiler says it is unable to determine the return type of the conditional operator.

Sascha
  • 1,210
  • 1
  • 17
  • 33
Tom Davies
  • 2,386
  • 3
  • 27
  • 44
  • 1
    http://stackoverflow.com/questions/10964065/conditional-operator-doesnt-work-with-two-types-that-inherit-the-same-base-type or http://stackoverflow.com/questions/4087304/the-c-sharp-conditional-operator-gets-confused-but-why – Tim Schmelter Jan 08 '16 at 09:39
  • 1
    Try `I mything = someBoolCondition ? new A() as I : new B() as I;`. – Enigmativity Jan 08 '16 at 09:39

2 Answers2

2

The compiler will only consider the types of the 2 operands and implicit conversions between them. It will not look for base types or implemented interfaces.

You will need to explicitly cast one of the operands to I.

From C# language specification:

The second and third operands, x and y, of the ?: operator control the type of the conditional expression.

• If x has type X and y has type Y then

o If an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.

o If an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.

o Otherwise, no expression type can be determined, and a compile-time error occurs.

If the compiler checked base types too, any combination of types would be valid - in the worse case, the result type would be object.

Community
  • 1
  • 1
Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
0

You need to cast one of the operands to I. Like this :

I mything = someBoolCondition  ?  (I) new A() : new B();
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109