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

1

32

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

Vase answered 15/4, 2014 at 16:4 Comment(5)
I'd assume it's just a stylistic difference, but I could be wrong. @Amicable that's mainly about different equality comparisons, not > vs CompareTo.Tickler
For TimeSpans, there is no difference. My guess is that the sample dev wasn't aware that overloaded operators existed.Assuage
@Amicable null comes before a string and it uses CultureInfo.CurrentCulture.CompareInfo.Compare, which means it will use a culture-dependant comparison. This might mean that ß will compare equal to SS in Germany, or similar - is not applicable to TimeSpanVase
They probably did not know that TimeSpan overloads these operators. Or they have a Java background.Dachi
Comparing structure types is iffy, you'd have to know the implementation. TimeSpan implements IComparable. Interfaces exist to encourage a programmer to code against the contract. So using IComparable.CompareTo() follows the practice. You are entirely free to ignore it of course, nobody is going to frown on it.Trappings
F
27

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

Fibro answered 15/4, 2014 at 16:12 Comment(1)
That is the link I was looking for for my own answer! +1Reeva

© 2022 - 2024 — McMap. All rights reserved.