There are a few things here. If I am going to implement any aspect of equality in a class such as GetHashCode , overriding == or IEquatable , I always use the following pattern.
- Override Equals
- Override GetHashCode
- Implement
IEquatable<T> , which means implementing Equals(T) - We realize! =
- Implementation ==
So, if I had a class called ExpiryMonth with the Year and Month properties, here is what this implementation would look like. This is a pretty pointless task to adapt to other types of classes now.
I based this template on several other stackoverflow answers that are all trustworthy, but which I did not track along the way.
Always implementing all of these elements together, it provides the right equality operations in various contexts, including dictionaries and Linq operations.
public static bool operator !=(ExpiryMonth em1, ExpiryMonth em2) { if (((object)em1) == null || ((object)em2) == null) { return !Object.Equals(em1, em2); } else { return !(em1.Equals(em2)); } } public static bool operator ==(ExpiryMonth em1, ExpiryMonth em2) { if (((object)em1) == null || ((object)em2) == null) { return Object.Equals(em1, em2); } else { return em1.Equals(em2); } } public bool Equals(ExpiryMonth other) { if (other == null) { return false; } return Year == other.Year && Month == other.Month; } public override bool Equals(object obj) { if (obj == null) { return false; } ExpiryMonth em = obj as ExpiryMonth; if (em == null) { return false; } else { return Equals(em); } } public override int GetHashCode() { unchecked
Steve lautenschlager
source share