Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 930
Refracted Paladin Avatar asked Aug 11 '10 15:08

Refracted Paladin


1 Answers

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.

like image 198
Yuriy Faktorovich Avatar answered Oct 14 '22 00:10

Yuriy Faktorovich