Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing DateTimes: DateTime.Compare() versus relational operators

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()?

like image 863
JYelton Avatar asked Apr 11 '11 17:04

JYelton


2 Answers

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.

like image 141
Reed Copsey Avatar answered Nov 18 '22 09:11

Reed Copsey


When you're passing the object as an IComparable, the "relational" operators are not available. In this case, it can be handy.

like image 6
spender Avatar answered Nov 18 '22 11:11

spender