I have class "A" that overloads "==" operator to allow instances be compared with instances of the same class "A" and instances of class "B".
It works ok but when I try to use "== null" (compare "A" class instance to null) compiler throws error:
Ambiguous invocation:
bool == (A, A)
bool == (A, B)
Is it possible to refactor class somehow to make "== null" compilable or ReferenceEquals is the only alternative (funny, but "Yoda condition" null == A-class-instance works ok)
The simplest way is just to cast:
if (a == (A) null)
That's assuming you want to call the overloaded operator. If you want to compare for reference equality, you can use either of these:
if (a == (object) null)
if (ReferenceEquals(a, null))
Personally I'd go with the second - I find it's more explicit and thus clearer.
My guess as to why the reversed version works is that there's no overload of ==(B, A)
.
Personally I would avoid overloading == like this anyway - it's highly unusual for instances of different types to compare as equal, particularly using ==. It's even worse if the operator hasn't been overloaded symmetrically:
bool x = (a == b);
bool y = (b == a);
If x
and y
can have different values here, you're really asking for a world of pain and hard-to-spot bugs. Just don't do it...
Cast null
to certain type, for example (A)null
. It will remove ambiguity. And null == null
and (a != null) && (b == null) -> (a != b)
, means that it is logically safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With