Search code examples
c#.neticomparable

IComparable behaviour for null arguments


I'm implementing IComparable and IComparable<T> in one of my classes. Is there any recommendation on how the CompareTo method in each case should behave when given a null argument? Should it return a positive number or throw an ArgumentNullException? Or can this behaviour vary depending on the implementing class?

I saw the MSDN documentation (here and here) but it has nothing to say on this subject. Any help will be appreciated.


Solution

  • Both MSDN references for IComparable.CompareTo() and IComparable<T>.CompareTo() state the following:

    By definition, any object compares greater than (or follows) Nothing, and two null references compare equal to each other.

    Nothing in VB corresponds to null in C#.

    Note that the previous paragraph states:

    The meaning of the comparisons, "less than," "equal to," and "greater than," depends on the particular implementation.

    But instance references that aren't null are always greater than null references, no matter how you compare instances of your class.