I should probably post that I don't think there is a solution, and I just decided to forsake symmetry and go with ==(Complex a, object b). Thanks to everyone who posted!
When defining the operator ==, null value returns "call is ambiguous"
-
29-05-2022 - |
Pergunta
I have custom classes Rational, Real, and Complex. In Complex I overload operators that allow me to compare a Complex and a Real, or a Complex and a Rational. It would be easy if I could define an implicit cast of a Rational to a Complex, say, but for reasons not worth going into, I can't.
Therefore I have, among others,
==(Complex a, Real b)
and also
==(Real a, Complex b)
Obviously when I try to compare
c==null
I get the error message that the call is ambiguous. I saw on a related thread the idea that I could just define ==(Complex a, object b)
I had thought of that, but then if I want to allow symmetry, I also need ==(object a, Complex b)
in which case a comparison between two complexes will also be ambiguous.
Right now when I check for null I'm having to cast the Complex to an object first. What's a better solution? (I'm hoping for a general solution rather than a solution that depends on any relationship between the classes e.g. inheritance.)
Solução 3
Outras dicas
I think that you have something like ==(Complex c, Real C)
and ==(Complex c, Complex C)
, of course the compiler won't know which one to choose, so when you compare to a null you have to cast it like c1 == (Complex) null
.
Why to use the second overload? Are you sure you cannot use first one for your checks? There is no "good-looking" solution you are looking for.