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.

2

4 Answers 4

3

How about this ?

decimal? d= myRdr["myValue"] == DBNull.Value ? null : (decimal?)myRdr["myValue"];
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

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

Comments

1

This should work:

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

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.