IDig IComparable
June 27th, 2007[ Geek ]
(Apologies for the code samples, indenting and justification is hosed so it ain’t pretty. I’ll fix that someday when all I have to do in a day is tinker with websites.)
Anytime I contemplate doing any of the following to a custom class: sorting, overriding Equals, overriding GetHashCode, or building typed collections, I typically start with IComparable. That is, I start by having the class implement IComparable.
Let’s say you’ve got a User class and it’s uniqueness is measured by it’s primary key in the database, represented by it’s Index property. I typically start by overriding GetHashCode(), so in this case you’d have:
public override int GetHashCode()
{
return this.Index;
}
The rules are that if GetHashCode is identical for two objects then they’re equal. So implementing IComparable is just a matter or relying on your GetHashCode:
public int CompareTo(object obj)
{
if (!(obj is User))
{
throw new ArgumentException();
}
User user2 = (User)obj;
int compare1 = this.GetHashCode().CompareTo(user2.GetHashCode());
return compare1;
}
Now that you’ve got a working CompareTo, you can use it for your Equals:
public override bool Equals(object obj)
{
if (this.CompareTo(obj) == 0)
{
return true;
}
return false;
}
If you asked me, that’s a clean, quick and simple way to have your objects support comparisons, hashing, and sorting using IComparable. As well, if you need a custom, strongly typed collection for you object then you can use CompareTo for comparison methods such as Contains, BinarySearch, etc.
Obviously this won’t handle every class and things will get more complicated but it takes care of the majority of cases and gets a strong foundation in place.