Home > Blockchain >  Most elegant way to stop getting CS8602 in VS2022, .NET 6, C# 10
Most elegant way to stop getting CS8602 in VS2022, .NET 6, C# 10

Time:03-29

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:

  1. Is it a bug in the compiler warning logic?
  2. 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.

CodePudding user response:

What is the most elegant way to stop getting the error?
In your project file delete <Nullable>enable</Nullable>

Is it a bug in the compiler warning logic?
No

Is there a better (meaning, short, not superfluous) way to write similar code?
"Better" is subjective. I think your code is fine, but this is what the warning wants you to do:

 XmlDocument doc = new XmlDocument();
 doc.LoadXml("<root/>");
 var nodes = doc?.SelectNodes("aaa");
 if (nodes == null)
 {
     //handle this case here
     return;
 }
 foreach (XmlNode node in nodes)
     Console.WriteLine(node.OuterXml);

Or you could do something like this:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<root/>");
foreach (var node in Enumerate(doc?.SelectNodes("aaa")))
    Console.WriteLine(node.OuterXml);

private static IEnumerable<XmlNode> Enumerate(XmlNodeList? list)
{
    if (list == null) yield break;
    foreach (XmlNode item in list)
    {
        yield return item;
    }
}

CodePudding user response:

I now understand that as GSerg commented, the API method being declared as XmlNodeList?(string) is the source of the warning (yet, it never returns null; it returns a non-null reference to an empty list).

My subjective "most elegant" solution that I found so far is to do this:

#pragma warning disable CS8602
foreach (XmlElement item in doc.SelectNodes("..."))
#pragma warning restore CS8602

because that suppresses just this instance, and I can benefit from other instances of this warning that, I dare say, are more legitimate.

  • Related