Both instances are instances of a class. What is the problem?
Operator ‘??’ cannot be applied to operands of type ‘A’ and ‘B’.
A myA = new A();
B myB = new B();
object? Ok1 = myA ?? myA; //Ok
object? Ok2 = myB ?? myB; //Ok
object? Error = myA ?? myB; //Error. Operator '??' cannot be applied to operands of type 'A' and 'B'
class A
{
}
class B
{
}
>Solution :
The problem is that the compiler can’t work out the "best type" to use for the expression. (It tries for either A or B, but doesn’t look for common types in the hierarchy.)
From the ECMA standard, section 12.15:
The type of the expression
a ?? bdepends on which implicit conversions are available on the operands. In order of preference, the type ofa ?? bisA₀,A, orB, whereAis the type of a (provided that a has a type), B is the type of b(provided that b has a type), andA₀is the underlying type ofAifAis a nullable value type, orAotherwise.
If you cast either of the operands to object?, it should be fine:
object? success = myA ?? (object?) myB;