Could anybody explain the following code return total ?? decimal.Zero please?
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 it mean the following?
if (total !=null) return total;
else return 0;
Yes, that’s what it means. It’s called the null-coalescing operator.
It’s just a syntax shortcut. However, it can be more efficient because the value being read is only evaluated once. (Note that there can also be a functional difference in cases where evaluating the value twice has side effects.)