I am using conversion to decimal
of a byte array
, such that it contains either null
or any other number, stored in byte. The problem here is, when I try to convert a null
to Nullable decimal
, it converts it to zero
. I want it to remain null
...
Convert.ToDecimal(obj.sal== null ? null : System.Text.Encoding.ASCII.GetString(obj.sal))
If you want the result to potentially be null, then you shouldn't be calling Convert.ToDecimal
- which always returns decimal
. Instead, you should use:
x = obj.sal == null ? (decimal?) null
: Convert.ToDecimal(Encoding.ASCII.GetString(obj.sal));
Note that you have to cast the null
literal to decimal?
- or use some other form like default(decimal?)
so that the type of the second operand is decimal?
- otherwise the compiler won't be able to infer the type of the conditional expression. See this question for more details on that.
See more on this question at Stackoverflow