简体   繁体   中英

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 

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.

Try this:

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

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

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;

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM