Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I use "== null" if "==" operator is overloaded to be compared with several class types

Tags:

c#

.net

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)

like image 380
Andrew Florko Avatar asked Dec 21 '22 18:12

Andrew Florko


2 Answers

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...

like image 190
Jon Skeet Avatar answered Jan 29 '23 07:01

Jon Skeet


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.

like image 39
Andrey Avatar answered Jan 29 '23 07:01

Andrey