Reputation: 865
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.
Upvotes: 1
Views: 4366
Reputation: 19171
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/
Upvotes: 0
Reputation: 3342
This should work:
decimal? d = myRdr["myValue"] == DBNull.Value ? null : decimal.Parse(myRdr["myValue"].ToString());
Upvotes: 1
Reputation: 101701
How about this ?
decimal? d= myRdr["myValue"] == DBNull.Value ? null : (decimal?)myRdr["myValue"];
Upvotes: 3
Reputation: 14614
Try this:
decimal? d = myRdr["myValue"] != DBNull.Value ? (decimal)myRdr["myValue"] : null;
Upvotes: 1