DBNull.Value To Decimal

by Svetlozar Angelov 26. January 2010 10:00

These day I had to read some data from SqlDataReader and populate a List of user-defined objects.

while (reader.Read())
{
    //populate the list
}

There was a few decimal values in my result set(as the user-defined object had decimal fields) so I needed a conversion to decimal. I was quite surprised that

Convert.ToDecimal(null)

returns 0.00, while

Convert.ToDecimal(DBNull.Value)

throws System.InvalidCastException. Investigating the nature of DbNull.Value I found out that you can not convert it to anything. However a simple extension method would do the trick 

public static class CustomExtensions
{
    public static Decimal ToDecimal(this SqlDataReader reader, string index)
    {
        if (reader[index] == DBNull.Value)
            return 0;
        else
            return Convert.ToDecimal(reader[index]);
    }
}

Tags:

programming

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen