Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast object to decimal? (nullable decimal)

If have this in the setter of a property:

decimal? temp = value as decimal?; 

value = "90"

But after the cast, temp is null...

What is the proper way to do this cast?

like image 648
Natrium Avatar asked Feb 09 '09 08:02

Natrium


People also ask

What is nullable decimal?

Nullable Types have the properties Value and HasValue . HasValue - Gets a value indicating whether the current Nullable object has a value. Value - If HasValue is true, this contains the value if not its null. decimal v2; if (v1.HasValue) // check for null { v2 = v1.Value; }

How do you convert a decimal number to a decimal?

Step 1 − Divide the decimal number to be converted by the value of the new base. Step 2 − Get the remainder from Step 1 as the rightmost digit (least significant digit) of new base number. Step 3 − Divide the quotient of the previous divide by the new base.


1 Answers

Unboxing only works if the type is identical! You can't unbox an object that does not contain the target value. What you need is something along the lines of

decimal tmpvalue; decimal? result = decimal.TryParse((string)value, out tmpvalue) ?                   tmpvalue : (decimal?)null; 

This looks whether the value is parsable as a decimal. If yes, then assign it to result; else assign null. The following code does approximately the same and might be easier to understand for people not familiar with the conditional operator ?::

decimal tmpvalue; decimal? result = null; if (decimal.TryParse((string)value, out tmpvalue))     result = tmpvalue; 
like image 118
Konrad Rudolph Avatar answered Sep 23 '22 08:09

Konrad Rudolph