As always, before you ask "how do I do this?", you should ask "has anybody already done this for me?"
public int CompareTo(object obj)
{
if(obj == null) { return 1; }
var other = obj as UpdateId;
if(other == null)
{
throw new ArgumentException("Object is not an UpdateId", "obj");
}
return this.AsTuple().CompareTo(other.AsTuple());
}
private IComparable AsTuple()
{
return Tuple.Create(Year, ReleaseNumber, Revision);
}
Note that this does have a potential performance overhead, so you should check anywhere that UpdateId
is being used in a tight loop (which will generally be if it's being sorted). One potential performance improvement- if the Year
, ReleaseNumber
and Revision
are immutable- would be to store the tuple in a private field so it does not need to be regenerated each time.
Note that as well as pushing the logic to an existing .NET class rather than trying to do it ourselves, we also:
- Invert the
ArgumentException
check. For some reason you do this for the null check but not the invalid argument type check or the ones that come later. As you can see from Heslacher's answer, this inversion makes the method much cleaner.
- We remove the redundant "
this
" keywords. Actually I did leave one in in the last line of CompareTo
because I think it makes it read better. But usually, they just clutter things up if they're not needed.
Realistically, it's unlikely that you're ever going to write anything that consumes IComparable
directly. Instead you're probably going to have .NET library methods do it for you. For this reason, consider using explicit interface implementation so that CompareTo
doesn't clutter up your class's public interface (e.g. in IntelliSense) unnecessarily.
If you do want to be able to compare versions individually rather than as a sort operation (e.g. "Is the current version installed less than the latest version?"), you can implement the comparison operators as RobH suggests