9

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 
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
makerofthings7
  • 60,103
  • 53
  • 215
  • 448
  • 2
    What's wrong with `int total = (myfavoriteNumber.HasValue) ? myFavoriteNumber.Value * 2 : 0;`? Still one line, and more readable than your suggested "new way" – Shadow The GPT Wizard Mar 13 '16 at 13:07
  • @ShadowWizard I am assuming that he might want to use this function several times hence the use of += so that he can keep a running total? I'm just guessing. I still liked your comment as I agree with you. – K-Dawg Mar 24 '16 at 09:54
  • @PrimeByDesign I would go with `??`, as in [this](https://stackoverflow.com/a/35970536/111794) answer. – Zev Spitz May 25 '17 at 11:40

4 Answers4

4

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.

mnwsmit
  • 1,198
  • 2
  • 15
  • 31
  • _what would that mean?_ Just as an aside, usually any number multiplied by NULL returns NULL. That's how normal SQL works, for example. NULL often means "I don't know the value". Imagine this example: I multiply 5 apples for NULL $ per apple. So I _don't know_ the cost of an apple. The consequence is that _I can't know_ the total cost, so the result is NULL. – Massimiliano Kraus May 19 '17 at 14:59
3

Try this:

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

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

3

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;
Pooven
  • 1,744
  • 1
  • 25
  • 44
Alberto Chiesa
  • 7,022
  • 2
  • 26
  • 53
0

Try this

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