Search code examples
nullnullreferenceexceptioncompareto

How to order null objects with compareTo in C#


I have a class called UserView and I implemented his compareTo() method.

I have that restriction: "If a UserView is compared with a null UserView, the null go before the other"

I have that compareTo():

 public int CompareTo(UserView other)
    {
        if (this == null && other != null) return -1;
        else if (this == null && other == null) return 0;
        else return Id.CompareTo(other.Id);
    }

And this test:

 [TestMethod]
    public void TestCompareWithNull()
    {
        UserView uv = new UserView(1, "pepe", "1234", "alumno", true);
        UserView uv2 = null;
        UserView uv3 = null;
        Assert.AreEqual(uv2.CompareTo(uv3), 0);
        Assert.AreEqual(uv2.CompareTo(uv), -1);
        Assert.AreEqual(uv.CompareTo(uv3), 1);
    }

When I call compareTo from uv2, which is null, I have NullReferenceException so... how Can I satisfy the given restriction?


Solution

  • If you want compare arbitraty instances (including both null case) you have to implement a static method, since

      this == null
    

    is an impossible condition within any member function. And so the immediate cause of the exception is calling a member function on null instance:

    UserView uv2 = null;
    // Since uv2 is null, Null Exception will be thrown
    uv2.CompareTo(uv3);
    

    A way out is a static method:

    public int CompareTo(UserView other) 
    {
        return UserView.Compare(this, other);   
    }
    
    // please, note "static" 
    public static int Compare(UserView left, UserView right)
    {
        if (left == null)
          if (right == null) 
            return 0;
          else 
            return -1;
        else if (right == null) 
          return 1; 
        else // Providing that Id can't be null (e.g. it's int)
          return left.Id.CompareTo(right.Id); 
    }
    
    ....
    
    UserView uv2 = null;
    UserView uv3 = null;
    
    // uv2.CompareTo(uv3) will throw Null Exception and
    // ... static UserView.Compare will do
    Assert.AreEqual(UserView.Compare(uv2, uv3), -1);