Why after this code execution variable 'a' contains null and not 10?
decimal? a = null;
a += 10;
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.
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
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