casting datareader value to a to a Nullable variable

Use the "IsDbNull" method on the data reader... for example:

bool? result = dataReader.IsDbNull(dataReader["Bool_Flag"]) ? null : (bool)dataReader["Bool_Flag"]

Edit

You'd need to do something akin to: bool? nullBoolean = null;

you'd have

bool? result = dataReader.IsDbNull(dataReader["Bool_Flag"]) ? nullBoolean : (bool)dataReader["Bool_Flag"]

Consider doing it in a function.

Here's something I used in the past (you can make this an extension method in .net 4):

public static T GetValueOrDefault<T>(SqlDataReader dataReader, System.Enum columnIndex)
{
    int index = Convert.ToInt32(columnIndex);

    return !dataReader.IsDBNull(index) ? (T)dataReader.GetValue(index) : default(T);
}

Edit

As an extension (not tested, but you get the idea), and using column names instead of index:

public static T GetValueOrDefault<T>(this SqlDataReader dataReader, string columnName)
{

    return !dataReader.IsDBNull(dataReader[columnName]) ? (T)dataReader.GetValue(dataReader[columnName]) : default(T);
}

usage:

bool? flag = dataReader.GetValueOrDefault("BOOL_COLUMN");

Tags:

C#

Sql