Search code examples
c#nullcalloperator-keywordambiguous

When defining the operator ==, null value returns "call is ambiguous"


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


Solution

  • 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!