akrobet
akrobet

Reputation: 119

Add nullable decimals in C#

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

Answers (2)

Carsten Schütte
Carsten Schütte

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

Marc Gravell
Marc Gravell

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

Related Questions