If null.Equals(null) why do I get a NullReferenceException

Viewed 26751

I have the following line of code:

var selectedDomainID = lkuDomainType.EditValue.Equals(null) 
    ? string.Empty 
    : lkuDomainType.EditValue;

Sometimes this generates a NullReferenceException. What I don't understand is why. Isn't the whole point of my code to check for null and if so assign string.empty? When I check in DEBUG it is stating that EditValue == null so what am I missing?

10 Answers

All current answers fail to address a critical point: the difference between calling Equals on a Nullable type (which is a struct) vs. class type.

Calling Equals on a Nullable typed object whose value is null will not issue an exception, while doing the same on a class typed object will.

Consider the following code:

int? num = null; // int? is Nullable<int>
String s = null; // String is a class

var equalsNullable = num.Equals(null); // works
var equalsClass = s.Equals(null);      // throws

The reason is that Nullable's HasValue method is called in such case, see Jon Skeet's answer for more info.

As other people said, the way to go in the OP's case is to use == or ??.

Related