Null checking is ambiguous for a class with several overrides for == operator
c#, equality, null-check, operator-overloading
Solution
Since you're using a `null` literal, the compiler doesn't know which method to call since both `string` and `SomeClass` can be null.
One technique to force the compiler to choose one of the methods is to typecast the null.
Console.WriteLine(someObject == ((SomeClass)null));
Or better yet, instead of using `null` explicitly, use the `default` keyword to get the null value (because `default(T)` is null when T is a reference type).
Console.WriteLine(someObject == default(SomeClass));
Problem
I have a class with two overrides for == operator, to compare it to other instances of this class, and to compare to instance of string. ``` class SomeClass { string value; public SomeClass (string _Value) { value = _Value; } static public bool operator == (SomeClass C1, SomeClass C2) { return C1.value == C2.value; } static public bool operator != (SomeClass C1, SomeClass C2) { return C1.value != C2.value; } static public bool operator == (SomeClass C1, string C2) { return C1.value == (string) C2; } static public bool operator != (SomeClass C1, string C2) { return C1.value != (string) C2; } } ``` However, when I try to compare this class to null: ``` Console.WriteLine(someObject == null); ``` I get the following error: ``` Error CS0121: The call is ambiguous between the following methods or properties: `SomeClass.operator ==(SomeClass, SomeClass)' and `SomeClass.operator ==(SomeClass, string)' ``` How should I define my == overrides so I can still null-check instances of this class?