I have the following interface:
interface IMyInterface {}
And the following two implementations:
class MyImplementation : IMyInterface {}
class MyOtherImplementation : IMyInterface {}
Given that, the following compiles:
IMyInterface ReturnImplementation()
{
if(condition)
{
return new MyImplementation();
}
else
{
return new MyOtherImplementation();
}
}
But this does not:
IMyInterface ReturnImplementation()
{
return condition ? new MyImplementation() : new MyOtherImplementation();
}
Why? What am I misunderstanding in assuming that it should compile? Is it as simple as the fact that the shorthand if
specifies the exact same type is chosen from? If so, why? Why is it restricted in this way?
What am I misunderstanding in assuming that it should compile?
You're not reading the spec :)
Basically, conditional operator requires that either the second and third operands are of the same type, or that there's an implicit conversion from one of them to the other (and not the other way round). In other words, the overall result type of the operator has to be either the type of the second operand or the type of the third operand.
That's the reason the compiler is giving you an error message about implicit conversions - you are asking it to try to implicitly convert either MyImplementation
to MyOtherImplementation
or vice versa.
In your case, you want the result type to be IMyInterface
- so you should cast one of the operands - either of them - to that type:
return condition ? (IMyInterface) new MyImplementation() : new MyOtherImplementation();
At that point the compiler will note that there's an implicit conversion from MyOtherImplementation
to IMyInterface
but not vice versa, and pick IMyInterface
as the overall type of the operator.
See more on this question at Stackoverflow