AngelicCore
AngelicCore

Reputation: 1453

If strings are nullable by default, why do i get Unable to cast object of type 'System.DBNull' to type 'System.String'.?

I have seen similar threads like this where the solution is a tertiary if.

My question is, why even get such an error if Strings are nullable?

I am reading a value of a text column in access using ado.net. Whenever there is a row with an empty text column i get that error.

Culprit:

while (dr.Read())
{
      UserList.Add(new UserInfo()
      {
        .
          DestributionGroup = (string)dr["Destribution Group"]
        .
      }
}
class UserInfo
{
.
    public string DestributionGroup;
.
}

Edit:

So in other words I have to convert all of my strings that I am reading from the DB into a line similar to this?

return (accountNumber == DBNull.Value) ? string.Empty : accountNumber.ToString ()

No other way around it?

Upvotes: 0

Views: 116

Answers (2)

Moe Sisko
Moe Sisko

Reputation: 12015

You can use this if you don't mind DestributionGroup being set to null when dr["Destribution Group"] is DBNull.Value :

DestributionGroup = dr["Destribution Group"] as string;

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460108

Because null != DBNull.Value.

But you can check if it the value in the DataReader is null with the IsDbNull method:

DestributionGroup = dr.IsDbNull("Destribution Group") ? "" : dr.GetString("Destribution Group");

Upvotes: 3

Related Questions