Search code examples
c#nullablesqldatareader

nullable decimal from SqlDataReader


I use SqlDataReader to read some values from SQL data table. Value is decimal, but it call also be null. How do I assign it? I have tried it like this, but it throws "Specified cast is not valid" exception, if myValue is null.

decimal? d= (decimal)myRdr["myValue"];

What is the best way to do this?

Thank you.


Solution

  • How about this ?

    decimal? d= myRdr["myValue"] == DBNull.Value ? null : (decimal?)myRdr["myValue"];