I am receiving the following error when trying to access an XML element that doesnt exist using linq:
A first chance exception of type 'System.NullReferenceException' occurred in Test.exe System.NullReferenceException: Object reference not set to an instance of an object.
bool exists = website.Parent
.Element("Exclusions")
.Elements("Exclusion")
.Where(x => thisKeyword.ToUpper().Contains((string)x.Value.ToUpper() ?? "~"))
.Any();
I can remedy the issue by simply using .Where(x => thisKeyword.Contains((string)x))
But I need to convert both thisKeyword
and the XML element value (if it exists) to upper case to get a case-insensitive comparison.
I was under the impression that ?? "~"
meant that "if whats the left is null use what is to the right. So in this case x
should become tilde, and therefore not validate against thisKeyword
(as it wont ever contain tilde). A crude method I agree...but it doesn't even work.
How can I protect against the NullReferenceException?