C # What does this line mean?

Can someone explain the following code return total ?? decimal.Zeroplease?

public decimal GetTotal()
{
    // Part Price * Count of parts sum all totals to get basket total
    decimal? total = (from basketItems in db.Baskets
                      where basketItems.BasketId == ShoppingBasketId
                      select (int?)basketItems.Qty * basketItems.Part.Price).Sum();
    return total ?? decimal.Zero;
}

Does this mean the following?

    if (total !=null) return total;
    else return 0;
+3
source share
5 answers

Yes, that is what it means. It was called the zero coalescing operator .

This is just a syntax shortcut. However, this may be more effective, since the read value is evaluated only once. (Note that there may also be a functional difference in cases where evaluating a value twice has side effects.)

+13
source

??in C # is called the coalescence operator. This is roughly equivalent to the following code

if (total != null) {
  return total.Value;
} else {
  return Decimal.Zero;
}

if ?? , . ?? total , if .

, total , . , , .

// Here SomeOperation happens twice in the non-null case 
if (SomeOperation() != null) {
  return SomeOperation().Value;
} else { 
  return Decimal.Zero;
}

// vs. this where SomeOperation only happens once
return SomeOperation() ?? Decimal.Zero;
+6

.

, :

 return (total != null) ? total.Value : decimal.Zero;
+4

. - . .

+2

( total, decimal.Zero)

, total null, decimal.Zero.

+1

All Articles