Invalid "possible System.NullReferenceException" warning?

I have the following code snipped:

-


if (destinationXmlDocument.DocumentElement == null)
    throw new ArgumentException("Destination XmlDocument has null
DocumentElement", "destinationXmlDocument");

XmlNodeList list =
sourceXmlDocument.GetElementsByTagName("DocumentTransport");
foreach (XmlNode node in list)
    destinationXmlDocument.DocumentElement.AppendChild(destinationXmlDocument.ImportNode(node,true));
-



ReSharper 6.0 is warning with an underline and a yellow mark in the error
bar that the "DesginationXmlDocument.DocumentElement" in the body of the
foreach loop is a potential null reference exception.  But it isn't, because
the if() statement above the foreach loop specifically precludes that
possibility.

Is this a bug in ReSharper, or am I missing something?

It wants to correct it to this, but I don't see any reason to have to put
the test inside the loop, given that destinationXmlDocument.DocumentElement
is a constant through the loop iterations:

XmlNodeList list =
sourceXmlDocument.GetElementsByTagName("DocumentTransport");
foreach (XmlNode node in list)
    if (destinationXmlDocument.DocumentElement != null)
        destinationXmlDocument.DocumentElement.AppendChild(destinationXmlDocument.ImportNode(node,true));

If I'm wrong, can someone explain this to me?

If ReSharper's wrong, will this be fixed in the upcoming 6.0 bugfix release?

1 comment

Hello Paul,

At the moment ReSharper doesn't track values of complex references (such
as 'destinationXmlDocument.DocumentElement') while doing 'Possible NRE' analysis.
That's because the value returned by 'DocumentElement' property can change
between the null check and the actual usage. In order to avoid this warning
(and a potential problem) you can extract a local variable:

var documentElement = destinationXmlDocument.DocumentElement;
if (documentElement == null)
throw new ArgumentException("Destination XmlDocument has null
DocumentElement", "destinationXmlDocument");
XmlNodeList list =
sourceXmlDocument.GetElementsByTagName("DocumentTransport");
foreach (XmlNode node in list)
documentElement.AppendChild(destinationXmlDocument.ImportNode(node,true));

Andrey Serebryansky
Senior Support Engineer
JetBrains, Inc
http://www.jetbrains.com
"Develop with pleasure!"

if (destinationXmlDocument.DocumentElement == null)
throw new ArgumentException("Destination XmlDocument has null
DocumentElement", "destinationXmlDocument");
XmlNodeList list =
sourceXmlDocument.GetElementsByTagName("DocumentTransport");
foreach (XmlNode node in list)
destinationXmlDocument.DocumentElement.AppendChild(destinationXmlDocum
ent.ImportNode(node,true));



0

Please sign in to leave a comment.