Old Way
int? myFavoriteNumber = 42;
int total = 0;
if (myfavoriteNumber.HasValue)
total += myFavoriteNumber.Value *2;
New way?
int? myFavoriteNumber = 42;
total += myFavoriteNumber?.Value *2; //fails
The null-propagation operator ?. will as it says, propagate the null value. In the case of int?.Value this is not possible since the type of Value, int, cannot be null (if it were possible, the operation would become null * 2
, what would that mean?). So the 'Old Way' is still the current way to do this.
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