Refracted Paladin Refracted Paladin - 1 month ago 6
C# Question

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

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

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.

Comments