Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IComparable behaviour for null arguments

I'm implementing IComparable and IComprable<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.

like image 568
Frederick The Fool Avatar asked Dec 27 '11 07:12

Frederick The Fool


3 Answers

Make sure to use Object.ReferenceEquals to test whether an argument passed to CompareTo is null. Avoid using == and != operators in CompareTo methods because someone might actually follow the MSDN suggestion to delegate those operators back to CompareTo method, which would in turn create an infinite loop and a stack overflow(!).

Here is a model how you might try to implement a CompareTo method:

public class Piano : IComparable<Piano>
{
    public float Mark { get; set; }

    public int CompareTo(Piano other)
    {
        // The very basic implementation of CompareTo

        if (object.ReferenceEquals(other, null))
            return 1;   // All instances are greater than null

        return Mark.CompareTo(other.Mark);
    }
}

The whole source code with explanations on this address.

like image 70
Zoran Horvat Avatar answered Nov 14 '22 23:11

Zoran Horvat


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.

like image 31
BoltClock Avatar answered Nov 14 '22 23:11

BoltClock


I saw the MSDN documentation but it has nothing to say on this subject

Yes it does, but not very clearly. The documentation states:

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

The documentation is confusing because it mixes idioms from C# (null) and VB (Nothing) in the same sentence. I'll mention it to the documentation manager.

Note that the same rule applies to nullable value types. If you are sorting a list of nullable integers, say, then 1 is considered to be greater than null for the purposes of sorting. Be careful; this is not how nullable integers compare by default in C#.

like image 12
Eric Lippert Avatar answered Nov 14 '22 23:11

Eric Lippert