Search code examples
c#.netnull-coalescing-operator

Possible to use ?? (the coalesce operator) with DBNull?


If I have code similar to the following:

while(myDataReader.Read())
{
  myObject.intVal = Convert.ToInt32(myDataReader["mycolumn"] ?? 0);
}

It throws the error:

Object cannot be cast from DBNull to other types.

defining intVal as a nullable int is not an option. Is there a way for me to do the above?


Solution

  • Can you use an extension method? (written off the top of my head)

    public static class DataReaderExtensions 
    {
        public static T Read<T>(this SqlDataReader reader, string column, T defaultValue = default(T))
        {
            var value = reader[column];
    
            return (T)((DBNull.Value.Equals(value))
                       ? defaultValue
                       : Convert.ChangeType(value, typeof(T)));
        }
    }
    

    You'd use it like:

    while(myDataReader.Read())
    {
      int i = myDataReader.Read<int>("mycolumn", 0);
    }