views:

74

answers:

2

I have an xml that I am querying. One of the nodes is missing. So when I call XElement.Value I get a null exception.

What is the best way to guard against this? I know I can write an extension method, but I am wondering is there something build into the language for this?

+2  A: 

use the null coalesce operator ??

Given an XElement elem:

var value = (string)elem ?? "empty";
Manu
That's the right answer, but it's worth pointing out that the important bit here is really that `XElement`'s explicit conversion to string will return null if the input is null - whereas `element.Value` will throw an exception.
Jon Skeet
so assuming XElement is null. string myvalue = (string) XElement; will have myvalue be null? string myvalue = XElement.Value; will throw an exception. string myvalue = (string) XElement ?? "empty"; will give myvalue a value of "empty"?
zachary
A: 

Please can you add more of your code, so that we can make a better suggestion?

EasyTimer