0

I am trying to fetch record into listarray as follows:

List<Car> lst = new List<Car>();

string str = "select * from Inventory"; 

using(SqlCommand cmd = new SqlCommand(str,this.sqlcon))
{
    SqlDataReader rdr = cmd.ExecuteReader();

    while (rdr.Read())
    {
        lst.Add(new Car 
                    {
                        CarId = (int)rdr["CarId"],
                        Make = (string)(rdr["Make"] ?? ""),
                        Color= (string)(rdr["Color"] ?? ""),
                        PetName = (string)(rdr["PetName"] ?? "")

                    });
    }

    rdr.Close();
}

Make,color and petname may have null values and thus I used the ?? operator. I get the following error

Unable to cast object of type system.dbnull' to 'system.string'.

What is the correct way of checking for null in this scenario?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Poongodi
  • 67
  • 1
  • 8

2 Answers2

8

DBNull isn't the same as null, so you can't use the ?? operator. You have to handle this case separately.

Replace:

Make = (string)(rdr["Make"] ?? ""),

with:

Make =  (rdr["Make"] == System.DBNull.Value ? "" : (string)rdr["Make"]),
fubo
  • 44,811
  • 17
  • 103
  • 137
1

SqlDataReader returns a DBNull object, which is not a C# null - it is an object representing a NULL value in the database.

You have a number of options, and creating a method to handle that might be most readable and save you on repeating code:

private static string GetStringOrEmpty(object dbValue){
    return dbValue == System.DBNull.Value ? string.Empty : (string)dbValue;
}

and then

Make = GetStringOrEmpty(rdr["Make"]),

Alternatively look into Dapper which is a very small but powerful ORM that will handle a lot of this stuff for you.

Gerino
  • 1,943
  • 1
  • 16
  • 21