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

Refracted Paladin picture Refracted Paladin · Aug 11, 2010 · Viewed 23.1k times · Source

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?

Answer

Yuriy Faktorovich picture Yuriy Faktorovich · Aug 11, 2010

Use lkuDomainType.EditValue == null, otherwise you are trying to call an instance method on a null object. But the better option might be lkuDomainType.EditValue ?? String.Empty. Also watch out for lkuDomainType being null, unless it is a class not an object.