The following code gives the error in the title on the second line in the Main function.
public class P {}
public class B : P {}
public class A : P {}
void Main()
{
P p = GetA()??GetB();
}
public A GetA()
{
return new A();
}
public B GetB()
{
return new B();
}
A simple tweak to the line like these
p = (P)GetA()??GetB();
or
p = GetA()??(P)GetB();
works.
I’m curious why the compiler doesn’t understand that both are child classes of the left hand side container and allow the operation without the cast?
The type of the argument on the left hand side must be compatible with the type on the right hand side or vice versa. In other words, there must exist an implicit conversion from
BtoAor fromAtoB.In the above, if there is an implicit conversion from
ytoxthen the type ofxbecomes the type of the expression. if there is no implicit conversion fromytox, but there is an implicit conversion fromxtoy, then the type ofybecomes the type of the expression. if no conversion exists in either direction, boom; compilation error. From the spec: