Both answers given so far are incorrect. The accepted answer is incorrect because it is accidentally repeated. Another answer is incorrect because it says null is not null.
Your operator implementations are not correct; they must handle zero inputs correctly.
Your implementation of GetHashCode is deeply broken; You are trying to enter a fourteen-digit number in a format that can take nine digits. Just call GetHashCode for a date; no need to go through this rigamarole turning it into a string and then turn it into a number!
The right way to write code is to use object.ReferenceEquals
to compare links instead of using the ==
and !=
; It's too easy to do random recursion.
A typical template is as follows:
public static bool operator ==(Task t1, Task t2) { if (object.ReferenceEquals(t1, t2)) return true; // All right. We know that they are (1) not the same object, and // (2) not both null. Maybe one of them is null. if (object.ReferenceEquals(t1, null)) return false; if (object.ReferenceEquals(t2, null)) return false; // They are not the same object and both are not null. return t1.dateDue == t2.dateDue; } public static bool operator !=(Task t1, Task t2) { // Simply call the == operator and invert it. return !(t1 == t2); } public override bool Equals(object t) { return (t as Task) == this; } public override int GetHashCode() { return this.dateDue.GetHashCode(); }
Other comparison operators remain as an exercise.
source share