Checking for null does not suppress null dereference warning in Visual Studio 2022

77 Views Asked by At

I have this simple method to get a value from a wrapped DataTable:

public string GetValue(int nodeID, string attributeName)
{
    DataRow row = this.dataTable.Rows[nodeID];
    var result = row.Field<string>(attributeName);
    return result.ToString() ?? string.Empty;
}

For some reason, Visual Studio insists there is a null dereference despite the null coalescing operator. The n. c. operator should return an empty string exactly when a null is encountered, right? What am I missing?

In the same class, there is this method overload with similar code, which doesn't raise the warning:

public string GetValue(string nodeName, string attributeName)
{
    var result = from row in this.dataTable.AsEnumerable()
                 where row.Field<string>("nodeID") == nodeName
                 select row.Field<string>(attributeName);
    return result.ToString() ?? string.Empty;
}
1

There are 1 best solutions below

0
On BEST ANSWER

In the first case, row.Field<string>(attributeName) returns a string? which is then used to invoke ToString, result?.ToString() ?? string.Empty should remove the warning.

In the second case, result is a non-null IEumerable<string> so no warning. Note that in this case result.ToString() will probably not produce the expected result.