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.
Because null is of type object (effectively untyped) and you need to assign it to a typed object.
x = obj.sal == null ? (decimal?) null
: Convert.ToDecimal(Encoding.ASCII.GetString(obj.sal));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With