2

Is there any way to convert from DB.Null to decimal in C#?

Like

Object[] returnvalue = new Object[1];
returnvalue[0] = null;
returnvalue[0] = Convert.ToDecimal(returnvalue[returnvalue.Length - 1]);

Though CLR is saying that DBNull.Value cannot be type casted. Still I want to know is there

any work around? Thanks in advance

2
  • Where's DBNull in your example? That's just a simple null. Commented Jul 12, 2009 at 9:54
  • DBNull is a little different from null. Null means there is no object available. DBNull means the value is unknown. If you get a DBNull back then by definition the value is not currently known to you. How can you convert that into a decimal? You'll need to decide on a default value yourself and assign it. Commented Jul 12, 2009 at 10:03

9 Answers 9

7

How do you expect to cast null to anything? It's null, nothing, nada...

That said, your best bet would be to check for DBNull (or null in the above case) and use/return/whatever default(decimal) instead, though null and DBNull both have a significant semantic difference from just a default value; they are the absence of a value, so this is probably not what you want to do.

Sign up to request clarification or add additional context in comments.

Comments

7

There is a big difference between DBNull and null; your example only shows null...

But in answer; not really... what value whould you give it?

You could test and use the default, or use Nullable<decimal> (aka decimal?):

With null (not DBNull)

decimal? valOrNull = (decimal?)returnvalue[0];

or to take DBNull into account:

object val = returnvalue[0];
decimal? valOrNull = (val == null || val is DBNull) ? (decimal?)null
            : (decimal?)val; // or convert if it is a string etc

Comments

4
        object foo = DBNull.Value;
        decimal d = 0;

        d = (decimal)(foo as decimal? ?? 0); // handles dbnull fine with default 0

        MessageBox.Show(d.ToString());

        foo = 1234M;

        d = (decimal)(foo as decimal? ?? 0); // handles dbnull fine with default 0

        MessageBox.Show(d.ToString());

1 Comment

Even shorter: Decimal d = foo as decimal? ?? 0m
3

Have you considered using a nullable-decimal for your return value?

Though you'd still have to explicitly handle DB.Null, as that's different to null, you'd be able to differentiate the cases.

The code might look something like this ...

if (value == DB.Null)
    return null;
else return decimal.Parse(value.ToString());

Comments

1

You can simply do this:

Object[] returnvalue = new Object[1];
returnvalue[0] = DBNull.Value; //null from database
returnvalue[0] = returnvalue[0] == DBNull.Value 
? null 
: (Nullable<decimal>) Convert.ToDecimal(returnvalue[returnvalue.Length - 1]);

1 Comment

Its possible to replace: returnvalue[0] == DBNull.Value to: Convert.IsDbNull(returnvalue[0]) Will Work as the same.
0

If DBNull were to be converted to a Decimal, what value would you expect that decimal to have?

I think there is a Decimal.TryParse() function which would fail more gracefully.

Comments

0

Would this help?

returnvalue[returnvalue.Length - 1] is DBNull ? 0 : (decimal?)returnvalue[returnvalue.Length - 1] ?? 0

Comments

0

We use the below method to cast DBNull fields to decimal values in C#. The case where the field might be null can be catered for when giving the value of the field to the variable using a shorthand if.

 cmd.Fill<Entity>(result, a => new Entity()
                {

                    EntityProperty = (decimal)(a["FieldName"] == DBNull.Value ? null : a["FieldName"]),

                });

Comments

0

It could looks like this:

private decimal GetDecimal(string v)
{
    decimal r = 0.00M;

    try {
        r = decimal.Round(Convert.ToDecimal(v.Replace("%", "").Replace("zł", "").Replace(" ", "")), 2);
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message.ToString());
    }

    return r;
}

Calling:

decimal val = GetDecimal(dataTable.Rows[i][j].ToString()),

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.