Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Operator error ?? for instances of two classes

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?? b depends on which implicit conversions are available on the operands. In order of preference, the type of a ?? b is A₀, A, or B, where A is the type of a (provided that a has a type), B is the type of b(provided that b has a type), and A₀ is the underlying type of A if A is a nullable value type, or A otherwise.

If you cast either of the operands to object?, it should be fine:

object? success = myA ?? (object?) myB;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading