Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use the Nullable Operator with the Null Conditional operator?

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 
like image 615
makerofthings7 Avatar asked Mar 13 '16 12:03

makerofthings7


1 Answers

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.

like image 117
mnwsmit Avatar answered Oct 17 '22 19:10

mnwsmit