Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The conditional operator gets confused, but why? [duplicate]

Assume two classes, both descendants of the same superclass, like this:

class MySuperClass{}
class A : MySuperClass{}
class B : MySuperClass{}

Then this assignment won't pass the compiler:

MySuperClass p = myCondition ? new A() : new B();

The compiler complains that A and B are not compatible (Type of conditional expression cannot be determined because there is no implicit conversion between 'A' and 'B' [CS0173] ). But they are both of type MySuperClass, so in my opinion this should work. Not that it's a big deal; a simple cast is all it takes to enlighten the compiler. But surely it's a snag in the C# compiler? Don't you agree?

like image 262
BaBu Avatar asked Nov 03 '10 13:11

BaBu


1 Answers

The results of the conditional should be of the same type. They are not.

From MSDN, (?: Operator):

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

Since A and B are not the same type and you don't seem to have defined an implicit conversion, the compiler complains.

like image 90
Oded Avatar answered Nov 15 '22 12:11

Oded