Nullable access in lambda warns about System.InvalidOperationException

For a webshop, suppose you have a List<ActionCode>, where ActionCode has a Nullable<decimal> DiscountAmount property.
The following piece of LINQ works correctly:


      decimal actionCodesDiscount =
        actionCodes.Where(actionCode => actionCode != null && actionCode.DiscountAmount.HasValue)
                   .Sum(actionCode => actionCode.DiscountAmount.Value);




However, Resharper warns that the second lambda .Sum(actionCode => actionCode.DiscountAmount.Value) possibly throws System.InvalidOperationException.
This is caused by ReSharper checking access to the Nullable<decimal>.Value to see if the code checks for HasValue.

I'm checking for HasValue though, but since I'm using the Linq Where, which is a different lambda, Resharper doesn't know that I'm checking for it.

This might be a known issue, but maybe this could be resolved by some additional checking...


Note: if I convert this to a foreach with Resharper quicktool this warning isn't present:

      decimal actionCodesDiscount = 0;
      foreach (IActionCode actionCode in actionCodes)
      {
        if (actionCode != null && actionCode.DiscountAmount.HasValue)
          actionCodesDiscount += actionCode.DiscountAmount.Value;
      }

Please sign in to leave a comment.