How to use "== null" if the "==" operator is overloaded to compare with several types of classes

I have a class "A" that overloads the operator == so that the instances are compared with instances of the same class "A" and instances of class "B".

It works fine, but when I try to use "== null" (comparing an instance of class "A" with null), the compiler throws an error:

Ambiguous invocation: bool == (A, A) bool == (A, B) 

Is it possible to somehow create a refactor class to make "== null" compiled or ReferenceEquals is the only alternative (funny, but the "Yoda condition" null == A-class-instance works fine)

+4
source share
4 answers

The easiest way is to simply quit:

 if (a == (A) null) 

Suppose you want to call an overloaded statement. If you want to compare for reference equality, you can use any of them:

 if (a == (object) null) if (ReferenceEquals(a, null)) 

Personally, I would go with the second - I find it more explicit and, therefore, more clear.

My guess about why the reverse version works is that there is no overload ==(B, A) .

Personally, I would avoid overloading == like this anyway - it is very unusual for instances of different types to compare as equal, especially using ==. This is even worse if the operator was not overloaded symmetrically:

 bool x = (a == b); bool y = (b == a); 

If x and y can have different meanings here, you are really asking for a world of pain and hard-to-reach mistakes. Just don't do it ...

+9
source

Enter null in a specific type, for example (A)null . This will eliminate the ambiguity. And null == null and (a != null) && (b == null) -> (a != b) means that it is logically safe.

+1
source

This problem is described here: http://msdn.microsoft.com/en-us/library/ms173147%28vs.80%29.aspx

To compare x (type A) with zero, use:

 if (((object) x) == null) 

or, more simply,

 if (null == x) 

This line works because null is of type Object here, and Object does not overload the '==' operator.

Official line: "Use ReferenceEquals or apply a type to an object to avoid a loop."

In your case, you do not see the endless loop referenced by Microsoft. This is due to the ambiguity of resolution. Ambiguity is actually a secondary issue.

+1
source

The reason for your iodine condition is that both of your operators have a left operator of type "A". Therefore, it can determine, based on the type of right operator, which of the called operators.

As other posters suggested, you need to drop it:

 if(a == (A)null) 
0
source

Source: https://habr.com/ru/post/1338840/


All Articles