makerofthings7
makerofthings7

Reputation: 61433

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 

Upvotes: 9

Views: 878

Answers (4)

Try this

int? myFavoriteNumber = 42; 
total += (myFavoriteNumber.Value!=null)? myFavoriteNumber.Value*2 : 0;

Upvotes: 0

Alberto Chiesa
Alberto Chiesa

Reputation: 7350

I think you misunderstood the use of null conditional operator. It is used to short circuit a chain of ifs to null, when one of the steps yields null.

Like so:

userCompanyName = user?.Company?.Name;

Please note that userCompanyName will contain null if user or user.Company is null. In your example total cannot accept null, so it's more about the use of ?? than anything else:

total = (myFavoriteNumber ?? 0) * 2;

Upvotes: 3

Mohamed ElHamamsy
Mohamed ElHamamsy

Reputation: 221

Try this:

int? myFavoriteNumber = 42; 
total += (myFavoriteNumber??0) *2; 

The expression (myFavoriteNumber?? 0) returns 0 in case of myFavoriteNumber is null.

Upvotes: 3

mnwsmit
mnwsmit

Reputation: 1173

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.

Upvotes: 4

Related Questions