简体   繁体   中英

Assign null to decimal using ternary operator

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM