سؤال

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.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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#.

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 (!) in a blink of an eye.

Here is a model how you might try to implement 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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top