0

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();
}
Alpha75
  • 2,140
  • 1
  • 26
  • 49
  • 2
    If both WService and WServiceStub implement IDisposable as well as IWService, which type should the expression `isStub ? new WServiceStub() : new WService()` have? – Heinzi Dec 28 '17 at 18:05

1 Answers1

0

It is because the type of the third operand must be convertable to the type of the second, it does not look at the left-hand side of the assignment when determining the result type of the expression.

SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23
  • 1
    That's not entirely accurate. The second can also be convertible to the type of the third. See https://stackoverflow.com/a/18260915/860585 – Rotem Dec 28 '17 at 18:02