I have the following sample code in VS 2022, C# .NET 6.0:
using System.Xml;
XmlDocument doc = new XmlDocument();
doc.LoadXml("<root/>");
foreach (XmlNode node in doc.SelectNodes("aaa"))
Console.WriteLine(node.OuterXml);
and am getting "CS8602: Dereference of a possibly null reference" at the doc.SelectNodes line. The code works in the sense that it does not fail but simply does nothing when it does not find a node named 'aaa'. If I put 'root', it finds it. So, as far as I see, I am doing nothing wrong and offending to the compiler.
Yet, the warning is there and seems wrong and therefore annoying. My two questions are:
- Is it a bug in the compiler warning logic?
- Is there a better (meaning, short, not superfluous) way to write similar code that searches for all nodes matching a certain XML query and to process them that does not generate the warning?
I found out that I can just add "#pragma warning disable CS8602", but that does not feel like a great solution. Ideally, I would like to take advantage of this warning in other cases that seem to me legitimate unlike this one.