Convertdecimal?todecimalinearlierversionsof.NET(C#Version7.3)

c#

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
 });

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

回答

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,


以上是Convertdecimal?todecimalinearlierversionsof.NET(C#Version7.3)的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>