What are the operators <,> supposed to do with one or both objects being set to 'Nothing'?

108 views Asked by At

Using 2 objects of the same type, I'm trying to implement < and >, but I can't seem to find any authoritative source on what to do with either or both being Nothing. In other words what the accepted practice or MSDN suggestions are.

Example code:

Private Shared _accessors As IEnumerable(Of Func(Of CmykColor, Decimal))
Public Shared Operator >(ByVal color1 As CmykColor, ByVal color2 As CmykColor) As Boolean
            //' A null object is always less than a non-null object
            If color1 Is Nothing OrElse color2 Is Nothing Then Return False
            Dim foundGreater As Boolean
            For Each prop In _accessors
                If prop(color1) < prop(color2) Then Return False
                If foundGreater = False AndAlso prop(color1) > prop(color2) Then foundGreater = True
            Next
            Return foundGreater
        End Operator

Accessors is my canonical method for centralizing an enumeration of the properties (all are decimal)

return false for both if either is Nothing?

I found a comment, but can't seem to verify or validate it that

A null object is always less than a non-null object

How do I handle Nothing?

2

There are 2 answers

1
Maslow On BEST ANSWER

This is what i was looking for:

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

From Msdn documentation on IComparable.CompareTo

I don't see any reasoning or drawbacks to following compareTo on this as a general rule. Then, for specific usages or context check if throwing an exception makes more sense.

3
decyclone On

Considering this an exceptional case, you could throw an exception.

You can also follow what framework does and return False.

Example:

Dim result As Boolean = (New DateTime() > New DateTime()) ' result is False

Edit

And to be consistent, language itself returns False with following code:

Dim result As Boolean = (Nothing > Nothing) ' result is False

Also, theoretically, if both are Nothing, both are equal. And no one is greater than or less than the other one.

For example,

1 > 1  ' False
1 < 1  ' False
1 == 1 ' True