1

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
  • 2
    "ToString() cannot return a null result" - Incorrect. The return type of Object.ToString is String?. Commented Sep 27, 2022 at 22:23
  • 1
    If the field is defined as not null, then when would you ever get a DBNull object? Could you not just do reader["UniqueID"].ToString() ?? string.Empty? Commented Sep 27, 2022 at 22:32

2 Answers 2

0

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.