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
The TimeSpan. Compare() method in C# is used to compare two TimeSpan values and returns an integer that indicates whether the first value is shorter than, equal to, or longer than the second value. The return value is -1 if span1 is shorter than span2, 0 if span1=span2, whereas 1 if span1 is longer than span2.
C# TimeSpan struct represents a time interval that is difference between two times measured in number of days, hours, minutes, and seconds. C# TimeSpan is used to compare two C# DateTime objects to find the difference between two dates.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With