Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XDocument.Root : Possible System.NullReferenceException

It looks like R# is detecting a possible null reference in the following code:

var importedDoc = XDocument.Parse(importedXml);
var importedElements = importedDoc.Root.Elements().ToList();

When accessing importedDoc.Root property. The awkward thing is that now I want to unit-test my method but I'm not able to pass importedXml so that the resulting XDocument.Root throws NullReferenceException. I have added null-checking code to throw exception if that is the case and I want to cover that branch:

if (importedDoc.Root == null)
    throw new NullReferenceException("There is no root element");

Can anyone provide a way to make this happen or, if not, at least explain how does R# come up with this code warning? Is the Root property not marked [NotNull] because there might be a different way to construct XDocument in which Root actually is null? If so, is not this a bug in System.Xml.Linq?

like image 288
AlinG Avatar asked Jun 30 '26 16:06

AlinG


1 Answers

resharper doesn't know about any type of runtime checks XDocument.Parse may or may not do to ensure there is a root level element. It just sees XDocument.Parse as the invocation of a function that may return null and suggests you should test for a null condition where you actually use a member of the returned object.

since importedDoc.Root realistically can't be null since XDocument.Parse will throw when doing the parse in that case, you can either turn off the resharper warning with a comment

// ReSharper disable once PossibleNullReferenceException
var importedElements = importedDoc.Root.Elements().ToList();

or you could just add the null checks yourself and re-raise the exception if you want like this to make resharper happy:

var importedDoc = XDocument.Parse(importedXml);
var importedElements = importedDoc?.Root?.Elements().ToList() ?? new List<XElement>();

if (importedElements.Count == 0) throw new InvalidOperationException("No root");

or you could totally ignore the whole thing knowing that this particular warning isn't completely valid in this scenario.

like image 64
Mike Corcoran Avatar answered Jul 02 '26 07:07

Mike Corcoran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!