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 Field that this check is rarely used.
Thus, is the reader.IsDBNull
the best/most efficient way to check for nulls?
I have created 2 sample methods:
public static decimal? GetNullableDecimal(SqlDataReader reader, string fieldName)
{
if (reader[fieldName] == DBNull.Value)
{
return null;
}
return (decimal)reader[fieldName];
}
public static decimal? GetNullableDecimal_2(SqlDataReader reader, string fieldName)
{
if (reader.IsDBNull(reader[fieldName]))
{
return null;
}
return (decimal)reader[fieldName];
}
Most of the time the fields are going to be null.
Thanks in advance!
I would not get too caught up in the which method is better, because both work and I have used both in code before.
For instance, here is a utility function I dug up from one of my old projects:
Usage:
If you want to check for null and handle it (as opposed to checking for null and alerting the program that it was null) you can use the
as
operator with the null-coalescing operator??
. So in my programHere's a simpler version of @Karl Anderson's answer:
Or even:
Direct casting seems to work just fine for either nullable or non-nullable types.