As a heads up I’m a C# newbie here coming from a Java background.
Can someone explain this code to me:
int? a = null; int b = 10; a = a + b; //a will equal null
Why does a
get the value of null
? Is there a way to force a
to equal 10? I’m sure it has something to do with b
being a value type and a
being a nullable value type?
From the Microsoft docs: “lifted operators produce null if one or both operands are null”
Just having some fun exploring the language.
Thanks all
a = a + b
breaks down into a = null + 10
. What would you expect that to add up to? Null does not mean zero, it means no data or undefined data.
To do what you want you’d write either a = (a ?? 0) + b
or a = (a + b) ?? b
.
Null coalescing operator
Thank you, I was thinking a
would be assigned the value of 10
even if the null
was encountered. I still have some studying to do!