c# - Comparing DateTimes: DateTime.Compare() versus relational operators -


here 2 ways of comparing 2 datetimes:

datetime = datetime.now; datetime = new datetime(2008, 8, 1);  // method 1 if (datetime.compare(then, now) < 0)     // ...  // method 2 if (then < now)     // ... 

.compare returns integer (-1,0,1) indicating whether first instance earlier than, same as, or later second instance.

my question is, why use .compare when can use relational operators (<,<=,==,>=,>) directly? seems me, using .compare, need employ relational operators anyway (at least in above example; alternatively create switch statement examining cases -1, 0 , 1).

what situations prefer or require usage of datetime.compare()?

typically, .compare methods on types used sorting, not doing direct comparisons.

the icomparable<t> interface, when supported on type, allows many framework classes sort collections correctly (such list<t>.sort, example).

that being said, if want able comparison within generic class or method, restricting generic arguments types implement icomparable or icomparable<t> allow use .compare() comparisons when concrete type unknown.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -