Is there a better/cleaner way to do this?
int stockvalue = 0;
if (!Convert.IsDBNull(reader["StockValue"]))
stockvalue = (int)reader["StockValue"];
IsNullOrEmpty() Method of C# If any string is not assigned any value, then it will have Null value. The symbol of assigning Null value is “ “or String. Empty(A constant for empty strings). This method will take a parameter that will be of System.
If the return value from the database for that column is NULL , this translates to DBNull. Value in code. You need to check for this as it won't successfully cast to byte[] .
Null is similar to zero pointer in C++. So it is a reference which not pointing to any value. DBNull. Value is completely different and is a constant which is returned when a field value contains NULL.
DBNull represents a nonexistent value returned from the database. In a database, for example, a column in a row of a table might not contain any data whatsoever. That is, the column is considered to not exist at all instead of merely not having a value. A DBNull object represents the nonexistent column.
The shortest (IMHO) is:
int stockvalue = (reader["StockValue"] as int?) ?? 0;
Explanation:
The way I handle this is
int? stockvalue = reader["StockValue"] as int?;
Very simple, clean and one line. If for some reason I absolutely can't have a null value (which I find poor reasoning for usually since I'd rather know if a value has meaning or if it was unitialized for a primitive type) I would do:
int stockvalue = (reader["StockValue"] as int?).GetValueOrDefault(-1);
I wrote an extension method several days ago. By using it you could just do:
int? stockvalue = reader.GetValue<int?>("StockValue");
Here's the extension method (modify to fit your needs):
public static class ReaderHelper
{
public static bool IsNullableType(Type valueType)
{
return (valueType.IsGenericType &&
valueType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)));
}
public static T GetValue<T>(this IDataReader reader, string columnName)
{
object value = reader[columnName];
Type valueType = typeof(T);
if (value != DBNull.Value)
{
if (!IsNullableType(valueType))
{
return (T)Convert.ChangeType(value, valueType);
}
else
{
NullableConverter nc = new NullableConverter(valueType);
return (T)Convert.ChangeType(value, nc.UnderlyingType);
}
}
return default(T);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With