Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add nullable decimals in C#

Tags:

c#

nullable

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.

like image 600
akrobet Avatar asked Mar 06 '26 06:03

akrobet


1 Answers

(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;
like image 165
Marc Gravell Avatar answered Mar 08 '26 19:03

Marc Gravell