1

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.

ekad
  • 14,056
  • 26
  • 43
  • 45
user1080533
  • 845
  • 2
  • 20
  • 34
  • possible duplicate of [Finding null value in Dataset - DataRow.IsNull method vs ==DbNull.Value - c#](http://stackoverflow.com/questions/5599390/finding-null-value-in-dataset-datarow-isnull-method-vs-dbnull-value-c-shar) – Nicholas Carey Feb 06 '14 at 18:33
  • Not a duplicate of [Finding null value in Dataset - DataRow.IsNull method vs ==DbNull.Value - c#](http://stackoverflow.com/questions/5599390/finding-null-value-in-dataset-datarow-isnull-method-vs-dbnull-value-c-shar), that is about testing if a value is null, this is about casting a nullable value from the reader to a variable – Andy Brown Feb 06 '14 at 18:48

4 Answers4

3

How about this ?

decimal? d= myRdr["myValue"] == DBNull.Value ? null : (decimal?)myRdr["myValue"];
Selman Genç
  • 97,365
  • 13
  • 115
  • 182
1

Try this:

decimal? d = myRdr["myValue"] != DBNull.Value ? (decimal)myRdr["myValue"] : null;
ekad
  • 14,056
  • 26
  • 43
  • 45
1

This should work:

decimal? d = myRdr["myValue"] == DBNull.Value ? null : decimal.Parse(myRdr["myValue"].ToString());
dub stylee
  • 3,192
  • 5
  • 37
  • 58
0
decimal? d = myRdr[columnName] as decimal?;

And the above, in an extension method:

public static decimal? GetNullableDecimal(this SqlDataReader myRdr, string columnName, decimal? valueIfNull = null)
{
    return myRdr[columnName] as decimal? ?? valueIfNull;
}

Usage:

decimal? d = myRdr.GetNullableDecimal("myValue");
decimal? d = myRdr.GetNullableDecimal("myValue", valueIfNull: 0);

footnote

Disclaimer. I've only read this, not tested it: "as" casting is said to be 5x faster than prefix (explicit) casting: http://gen5.info/q/2008/06/13/prefix-casting-versus-as-casting-in-c/

Andy Brown
  • 18,600
  • 3
  • 50
  • 61