Convert decimal? to decimal in earlier versions of .NET (C# Version 7.3)

Boj*_*ski 3 c# decimal type-conversion c#-7.3

So after searching for similar questions, I haven't seen any results.

The error that keeps popping up is

Feature 'target-typed conditional expression' is not available in C# 7.3. Please use language version 9.0 or greater.

The code:

.Select(x => new FinancialStatementDto
 {
   Uid = Guid.NewGuid(),
   AccountNumber = x.Key.AccountNumber,
   Credit = x.Any(y => y.Credit.HasValue) ? Math.Abs((decimal)x.Sum(y => y.Credit)) : null,
   Debit = x.Any(y => y.Debit.HasValue) ? x.Sum(y => y.Debit) : null,
   AccountName = x.Key.AccountName
 });
Run Code Online (Sandbox Code Playgroud)

The error pops up on Credit = x.Any(y => y.Credit.HasValue) ? Math.Abs((decimal)x.Sum(y => y.Credit)) : null,

Credit is defined as decimal? however the Math.Abs function doesn't allow nullable values.

Any ideas?

P.S. It must be done on version 7.3

das*_*ght 5

The problem is that the left side of your conditional is a non-nullable decimal, while the right side is null. There is no conversion between the two, and the language prior to C# 9 does not care about the target of the assignment being the common type (i.e. decimal?).

Adding a cast to decimal? on the left side will fix the issue:

Credit = x.Any(y => y.Credit.HasValue)
    ? (decimal?)Math.Abs((decimal)x.Sum(y => y.Credit))
    : null,
Run Code Online (Sandbox Code Playgroud)