Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of decimal nullable and decimal values

Tags:

c#

Why after this code execution variable 'a' contains null and not 10?

decimal? a = null;
a += 10;
like image 345
user2598794 Avatar asked Dec 09 '22 04:12

user2598794


2 Answers

You can't add a value to null. null will be null whatever value you add to it. On the other hand if you had assigned non null value to a the 10 would have been added to a.

Taken from MSDN

The predefined unary and binary operators and any user-defined operators that exist for value types may also be used by nullable types. These operators produce a null value if the operands are null; otherwise, the operator uses the contained value to calculate the result. For example:

int? a = 10;
int? b = null;

a++;         // Increment by 1, now a is 11.
a = a * 10;  // Multiply by 10, now a is 110.
a = a + b;   // Add b, now a is null.
like image 51
Christos Avatar answered Dec 10 '22 18:12

Christos


I don't know for c#, but in SQL, Null + value = Null, so that seems normal to me. In VBA I use Nz(myNum,0) to return 0 if myNum is Null, otherwise it returns myNum

like image 43
iDevlop Avatar answered Dec 10 '22 18:12

iDevlop