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;
}
In the first case,
row.Field<string>(attributeName)
returns astring?
which is then used to invokeToString
,result?.ToString() ?? string.Empty
should remove the warning.In the second case,
result
is a non-nullIEumerable<string>
so no warning. Note that in this caseresult.ToString()
will probably not produce the expected result.