Consider the following class:
public class Code : IEquatable<Code> { public string Value { get; set; } public override bool Equals(object obj) { return Equals(obj as Code); } public override bool Equals(Code code) { if (code == null) return false; return this.Value == code.Value; } public static bool operator ==(Code a, Code b) { if (a == null) return b == null; return a.Equals(b); } public static bool operator !=(Code a, Code b) { if (a == null) return b!= null; return !a.Equals(b); } // rest of the class here } Now try using the == method:
Code a = new Code(); Code b = new Code(); Console.WriteLine("The same? {0}", a==b); The result is a StackOverflowException because the == method calls itself when it checks for null.
But if I take out the null check:
public static bool operator ==(Code a, Code b) { return a.Equals(b); } I get a NullReferenceException!
What's the correct way to define these methods?
If you think of it from a programming (i.e. pointer reference) point of view then, yes, two references of null have the same pointer value and, since most of the popular languages will fall back to pointer-equality if no custom equality is defined, null does equal null.
operator is known as Null-coalescing operator. It will return the value of its left-hand operand if it is not null. If it is null, then it will evaluate the right-hand operand and returns its result. Or if the left-hand operand evaluates to non-null, then it does not evaluate its right-hand operand.
You can also use (object)a == null
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