Andy J Andy J - 1 year ago 79
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))

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

First I was very surprised, then I recalled something that
, 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))

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


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 Source

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

    ReferenceEquals(self, null) 
    && ReferenceEquals(other, null)
    !ReferenceEquals(self, null) 
    && !ReferenceEquals(other, null) 
    && self.Equals(other);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download