سؤال

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.)

نصائح أخرى

The ?? in C# is called the null coalescing operator. It's roughly equivalent to the following code

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

The one key difference between the above if statement expansion and the ?? operator is how side effects are processed. In the ?? example the side effects of getting the value total only happen once but in the if statement they happen twice.

In this case it doesn't matter because total is a local hence there are no side effects. But this can be a factor if say it's a side effecting property or method call.

// 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;

It's the null coalescing operator.

Effectively, it's like rewriting the code this way:

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

You nailed it. It's called the null-coalescing operator. Check it out here.

It returns the first non-null expression (the first expression being total, and the second expression being decimal.Zero)

So if total is null, decimal.Zero will be returned.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top