Here are two ways of comparing two DateTimes:
DateTime now = DateTime.Now;
DateTime then = new DateTime(2008, 8, 1);
// Method 1
if (DateTime.Compare(then, now) < 0)
// ...
// Method 2
if (then < now)
// ...
.Compare
returns an integer (-1,0,1) indicating whether the first instance is earlier than, the same as, or later than the second instance.
My question is, why would I use .Compare
when I can use relational operators (<
,<=
,==
,>=
,>
) directly? It seems to me, using .Compare
, I need to employ relational operators anyway (at least in the above example; alternatively I could create a switch statement examining cases -1, 0 and 1).
What situations would prefer or require usage of DateTime.Compare()
?
Typically, the .Compare
methods on types are used for Sorting, not for doing direct comparisons.
The IComparable<T>
interface, when supported on a type, allows many framework classes to sort collections correctly (such as List<T>.Sort
, for example).
That being said, if you want to be able to do a comparison within a generic class or method, restricting your generic arguments to types which implement IComparable
or IComparable<T>
will allow you to use .Compare()
for comparisons when a concrete type is unknown.
When you're passing the object as an IComparable
, the "relational" operators are not available. In this case, it can be handy.
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