Why use TimeSpan.CompareTo() rather than < > or =

Maxim Gershkovich picture Maxim Gershkovich · Apr 15, 2014 · Viewed 12.7k times · Source

I've been going over some Microsoft samples of code for the Kinect sensor and have stumbled across the following line.

TimeSpan zeroDuration = TimeSpan.FromSeconds(0.0);
TimeSpan timeRemaining = ...;

if (timeRemaining.CompareTo(this.zeroDuration) > 0)
{
}

I understand how CompareTo() is useful in scenarios such as sorting but why would it be used in a conditional if() instead of the more direct approach?

if (timeRemaining > this.zeroDuration)
{
}

PS: I would take it with a grain of salt if it was from any other source but given the general quality of the code assume there is a reason

Answer

Habib picture Habib · Apr 15, 2014

Both internally does the same thing. Compare Ticks and return result.

public int CompareTo(TimeSpan value) {
    long t = value._ticks;
    if (_ticks > t) return 1;
    if (_ticks < t) return -1;
    return 0;
}

 public static bool operator <(TimeSpan t1, TimeSpan t2) {
            return t1._ticks < t2._ticks;
}

The only reason could be the other overload for CompareTo, which receives an object type parameter checks for null and then compare. Implemented like:

public int CompareTo(Object value) {
            if (value == null) return 1;
            if (!(value is TimeSpan))
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeTimeSpan"));
            long t = ((TimeSpan)value)._ticks;
            if (_ticks > t) return 1;
            if (_ticks < t) return -1;
            return 0;
        }

Source code from: Reference Source .NET Framework 4.5.1 - Microsoft