Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign null to decimal using ternary operator

Tags:

c#

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))
like image 632
faizanjehangir Avatar asked Dec 08 '22 12:12

faizanjehangir


2 Answers

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.

like image 155
Jon Skeet Avatar answered Dec 21 '22 23:12

Jon Skeet


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));
like image 39
Vinay Pratap Singh Bhadauria Avatar answered Dec 21 '22 23:12

Vinay Pratap Singh Bhadauria