Reputation: 119
Let me reformulate. I am inside a ForEach loop what is supposed to add calculated decimal? values to the decimal? originalAmount that is of course null on the first time as you pointed out. So I just need to check null first otherwise do the addition.
decimal? convertedAmount = Calculate(inputValue); //always returns a value
originalAmount = originalAmount==null ? convertedAmount : originalAmount + convertedAmount;
The originalAmount is defined earlier, outside the loop.
Sorry for the confusion, the question can be closed / deleted if necessary.
Upvotes: 2
Views: 12125
Reputation: 4558
You need to specify how your addition should behave when one or both values are null. As a suggestion try something like this:
decimal? convertedAmount = ...
decimal? originalAmount = ...
if (convertedAmount.HasValue)
{
originalAmount = originalAmount.GetValueOrDefault() + convertedAmount.Value;
}
Upvotes: 3
Reputation: 1062895
(from comments)
I only want the originalAmount to have a value if the convertedAmount has, otherwise it should be null.
So:
decimal? convertedAmount = ...
decimal? originalAmount = convertedAmount;
which does everything in that requirement.
You could be more verbose, but this serves no purpose:
// unnecessary: don't do this:
decimal? originalAmount =
convertedAmount.HasValue ? convertedAmount.Value : (decimal?)null;
Upvotes: 6