XElement explicit operator throws an exception when XElement is null

41 Views Asked by At

XElement has explicit operators for nullables. For example Nullable<Int32>.

The sample provided by Microsoft appears to accommodate null values in the WriteLine, but if you provide a null it throws a FormatException and only seems to work if providing a non null value.

XElement root = new XElement("Root",   
    new XElement("Value", null)  
);  
int? value = (int?)root.Element("Value");  
Console.WriteLine("Nullable integer: value={0}", value == null ? "null" : value.ToString());

The documentation provided by Microsoft seems to suggest a FormatException should only occur if:

The element is not null and does not contain a valid Int32 value.

Have I missed something obvious, or is this not working as designed? Assuming I haven't missed anything is there a convenient way to deal with nullable elements? Currently the best I've come up with is:

int? value = Int32.TryParse((string)item.ElementOrException("Value"), out var tempVal) ? tempVal : default(int?);
1

There are 1 best solutions below

0
Etienne de Martel On BEST ANSWER

According to the documentation:

The element is not null and does not contain a valid Int32 value.

(emphasis mine)

The way it's phrased, even though it's a bit vague, implies that the thing that's allowed to be null is the element, not its value, as null is not a a valid int32.

And, indeed, by looking at the source:

public static explicit operator int?(XElement? element)
{
    if (element == null) return null;
    return XmlConvert.ToInt32(element.Value);
}

XmlConvert.ToInt32 simply calls int.Parse with some specific flags.

So, you could say it's a documentation failure, but the behaviour is as designed.

As for a workaround, I guess you could make your own extension method.