Assign null to decimal using ternary operator

I use the conversion to decimalfor byte array, so that it contains either null, or any other number stored in the byte. The problem here is that when I try to convert nullto Nullable decimal, it converts it to zero. I want him to stay null...

Convert.ToDecimal(obj.sal== null ? null : System.Text.Encoding.ASCII.GetString(obj.sal))
+4
source share
2 answers

If you want the result to be potentially empty, you should not call Convert.ToDecimal- which always returns decimal. Instead, you should use:

x = obj.sal == null ? (decimal?) null 
                    : Convert.ToDecimal(Encoding.ASCII.GetString(obj.sal));

, null decimal? - - , default(decimal?), decimal? - . . .

+12

null ( ), .

x = obj.sal == null ? (decimal?) null 
                : Convert.ToDecimal(Encoding.ASCII.GetString(obj.sal));
+1

All Articles