XPathNodeIterator Current

In the C# code below, R# 5.1 and R# 6.0 both report a possible NullReferenceException for iter.Current.  I don't understand how this can be.

According to MSDN, if iter.MoveNext() returns true "it moves the XPathNavigator object returned by the Current property to the next node in the selected node set", so I believe that the while loop can only be entered if iter.Current has been set.

Why then does R# report a possible NullReferenceException? Am I missing something or is this a bug?

string xmlTest;

XmlDocument doc = new XmlDocument();

XPathNavigator nav = doc.CreateNavigator();

XPathNodeIterator iter = nav.Select("/valid/path");
while (iter.MoveNext())
      XPathNodeIterator users = iter.Current.Select("");


Definitely, ".Current" could be null (for example, if enumerable collection contains 'null' inside). But it looks like ReSharper is too pessimistic here :).
We'll fix the annotations.


Thanks for the reply.

I'm still puzzled. I understand that in the general case of an enumerable collection then an item can be null, but in the case of an XPathNodeIterator how can this be?

If it is possible please could you give me an example, OR when you said that R# was being too pessimistic, did you mean that it should be treating an XPathNodeIterator differently as it is not possible for ".Current" to be null?


If you forget to check for "iter.MoveNext()", the iterator could be null


Please sign in to leave a comment.