I got a strange behaviour and I would like to understand it. But I haven't found good answers on the web :(
Here's the situation, I've abstracted the name and logic to focus on the issue. Got 3 types, A, B and C. B & C have implicit operators defined to convert to A object.
public class A
{
public static implicit operator A(B input){ /* Convert B to A */ }
public static implicit operator A(C input) { /* Convert C to A*/ }
}
public class B { }
public class C { }
Then, when I do this, the code compile and work fine :
A myObject = null;
if (condition)
myObject = new B();
else
myObject = new C();
But when I write the same logic with an inline if, I got an error :
A myObject = condition ? new B() : new C();
The error :
Type of conditional expression cannot be determined because there is no implicit conversion between 'B' and 'C'
Do you have any idea about this behaviour ?
Thank's in advance for your time.
Best regards and keep it bug free !
Do you have any idea about this behaviour ?
Absolutely. The type of a conditional operator expression must either be the type of the second operand or the type of the third operand. (And if those two types aren't the same, exactly one of the types has to be implicitly convertible to the other.) The compiler doesn't try to find a "lower common denominator" type, and the use of the result isn't important either (the compiler doesn't "notice" that you're assigning the result to a variable of type A
).
You can fix this yourself by just explicitly casting either operand:
A myObject = condition ? (A) new B() : new C();
or
A myObject = condition ? new B() : (A) new C();
Note that this isn't limited to user-defined conversion operators; the same is true for simple reference conversions based on derived classes:
Button x = new Button();
String y = "foo";
object z = condition ? x : y; // Compile-time error
See section 7.14 of the C# specification for more details.
See more on this question at Stackoverflow