How to resolve this SqlDataReader "Possible null reference assignment" warning?

656 views Asked by At

I just cannot figure out what is needed to resolve the warning about the possible null reference assignment in the following case:

item.UniqueId = Convert.IsDBNull(reader["UniqueID"]) ? string.Empty : reader["UniqueID"].ToString()

If the field value is NULL, it should set the property to an empty string, otherwise it should set it to the field value converted to a string. The field is defined as PK, varchar(11), not null.

if I define the UniqueID property as string? then the warning goes away, but it cannot be null so I don't want to do that.

I was under the impression that ToString() cannot return a null result.

2

There are 2 answers

0
SiBrit On BEST ANSWER

As per @codeMonkey's comment, the warning can be resolved by checking for the null return of the ToString() method.

item.UniqueId = reader["UniqueID"].ToString() ?? string.Empty;
0
T.S. On

I don't code like this. I write extensions that I use with my implementations with IDataReader. And this covers all DB providers I use, for example MySqlDatareader, SqlDataReader, OracleDataReader

public static string GetStringValue (this IDataReader r, sting f, string d) // f - field, d - default
{
    if (DBNull.Value.Equals(r[f]) || r[f] == null)
        return d;
    
    return r[f].ToString();
}

Usage

string x = null;
if (reader.Read())
    x = reader.GetStringValue("fieldName", "defaultValue or null");