Does the method CompareTo()
use GetHashCode()
to define to the object a comparable (not the interface) number? If I do
MyObject.CompareTo(MyOtherObject.GetHashCode())
What will happen if I don't want to override the CompareTo()
method ?
No, CompareTo does not / should not use GetHashCode to check for equality.
They might (emphasis on might) use it to determine inequality, if the hash code is cached and thus cheaper to look at than comparing all the internal data, but equal hash codes does not necessarily mean equal objects.
If you implement Equals and GetHashCode (you need to implement both or none), then here are the rules you should follow:
If it's an object you're creating yourself then here are some rules:
IComparable<T>
if you need ordering support. Don't implement CompareTo only to get equality checkes.IEquatable<T>
if you need equality checks.If it's an object you cannot modify, create:
IComparer<T>
to support orderingIEqualityComparer<T>
to support equality checksMost collections or methods that will do ordering or equality checks allows you to specify an extra object that determines the rules for the ordering or equality checks, assuming that either the implementation built into the object is wrong (possibly in just this single scenario) or missing.
Links to all the types:
System.IComparable<T>
and its external sibling System.IComparer<T>
System.IEquatable<T>
and its external sibling System.IEqualityComparer<T>