If I can assign any subtype to a supertype reference (upcasting):
IWService wService;
wService = new WService();
wService = new WServiceStub();
Why can I not assign them in a conditional operator ? :
?
IWService wService = isStub ? new WServiceStub() : new WService();
I get this error:
Type of conditional expression cannot be determined because there is no implicit conversion between MyNamespace.WServiceStub and MyNamespace.WService
But it's enough to cast one of them to the supertype to compile:
IWService wService = isStub ? (IWService)new WServiceStub() : new WService();
or
IWService wService = isStub ? new WServiceStub() : (IWService)new WService();
I don't understand why I need an explicit cast if I'll never get InvalidCastException
. The conversion is always sure, isn't it?
Is not the following code exactly the same?
IWService wService;
if (isStub)
{
wService = new WServiceStub();
}
else
{
wService = new WService();
}