I use the following line to convert the datarow
value into double.
double.parse(Convert.ToString(datarow));
If the datarow
Another alternative would be to check if the datarow
is DBNull
:
double d = datarow is DBNull ? 0 : double.Parse(Convert.ToString(datarow));
This way, you do not need to check for DBNull.Value
I have a bunch of conversion utility methods for such scenarios, in the format similar to this.
// tries to convert a general object to double, if a defaultValue is provided, it will silently fall back to it, if not, it will throw exceptions
public static double ToDouble(object obj, double? defaultValue = null) {
if (obj == null || obj == "" || obj == DBNull.Value) return 0.0;
try {
if (obj is string)
return double.Parse((string)obj);
return Convert.ToDouble(obj);
} catch {
if (defaultValue != null) return defaultValue.Value;
throw;
}
}
I use this kind of weak-to-strong type conversion utilities mostly when I work with ADO.NET stuff, or other weakly typed interfaces, like reading data from Excel for example.
In my real code I also allow to pass a CultureInfo
for string conversion, and do some other stuff like normalizing decimal signs, etc. to achieve the best format tolerance.
The general catch clause could be improved of course by catching specific exception types like FormatException
, but for my needs it works good.
DBNull
can't be cast or parsed to double
(or int
, decimal
, etc), so you have to check if datarow
is DBNull
before trying to parse it. It should be a oneliner using the ternary operator:
doubleValue = datarow == DBNull.Value ? 0.0 : double.Parse(Convert.ToString(datarow));