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.

有帮助吗?

解决方案

How about this ?

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

其他提示

Try this:

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

This should work:

decimal? d = myRdr["myValue"] == DBNull.Value ? null : decimal.Parse(myRdr["myValue"].ToString());
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/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top