Andy J Andy J - 2 months ago 7
C# Question

Correct handling of null

I try the following and get a crash about object reference not being set.

Thing thing = GetSomeThing(...);
if (thing != null && thing.Cool && thing.OwnedBy(someBody))
results.Add(thing);


When I hover over the thing after
GetSomeThing
I see it's
null
. But when I hover over
thing!=null
I get it to
true
. That's confusing!

First I was very surprised, then I recalled something that
null!=null
, which would explain the behavior. So I refactored into the following but for some reason it's still missing the first condition.

Thing thing = GetSomeThing(...);
if (thing == null) ;
else if(thing.Cool && thing.OwnedBy(someBody))
results.Add(thing);


What can I do about it? I am returning
null
from the method (of type
Thing
) so it seems right that far. But how to protect against the crash?

EDIT

class Thing
{
public string Name { get; set; }

public override bool Equals(object input)
{
Thing other = thing as Thing;
return !ReferenceEquals(other, null)
&& Name == other.Name;
}

public static bool operator ==(Thing self, Thing other)
{
return !ReferenceEquals(self, null)
&& !ReferenceEquals(other, null)
&& self.Equals(other);
}

public static bool operator !=(Thing self, Thing other)
{
return !(self == other);
}
}

Answer

@Igor You beat me to it, hehe.

There's a problem in your operator override. You're missing that null != null is supposed to be false in C#. In your implementation, null seems to be both not equal and not different from another null. Please try the following instead.

  return 
    ReferenceEquals(self, null) 
    && ReferenceEquals(other, null)
    ||
    !ReferenceEquals(self, null) 
    && !ReferenceEquals(other, null) 
    && self.Equals(other);
Comments