I want to retrieve decimal values from the database and I would like to know which is the recommended way to check for null values.
I have seen on MSDN - DBNull.Value F
Here's a simpler version of @Karl Anderson's answer:
public static class DbHelper
{
public static T GetValue(this SqlDataReader sqlDataReader, string columnName)
{
var value = sqlDataReader[columnName];
if (value != DBNull.Value)
{
return (T)value;
}
return default(T);
}
}
Or even:
public static class DbHelper
{
public static T GetValue(this SqlDataReader sqlDataReader, string columnName)
{
var value = sqlDataReader[columnName];
return value == DBNull.Value ? default(T) : (T) value;
}
}
Direct casting seems to work just fine for either nullable or non-nullable types.