Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting int to int? possible update?

I built my project locally and it worked with a code similar to the following:

bool success = true;
int y = 0;
int? x = success ? y : null;

But our build machine failed with the following error:

error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'

So, I had to update the code to:

bool success = true;
int y = 0;
int? x = success ? (int?)y : null;

That made the build machine build the project properly. I am assuming that happened due to some kind of update I had locally that the build machine didn't have. Maybe a C# update, but I couldn't find anything. Does anybody know if there was any update related to this recently and do you have a link to a documentation?

System info:

  • Visual Studio Community 2019 for Mac
    • Version 8.8.3 (build 16)
      • GTK+ 2.24.23 (Raleigh theme)
      • Xamarin.Mac 6.18.0.23 (d16-6 / 088c73638)
      • Package version: 612000107
like image 662
Marcelo Avatar asked Dec 03 '20 19:12

Marcelo


2 Answers

As mentioned in the comments, you'll need C# 9.0 (or later) to use such "target-typed" conditionals.

For example, with VS 2019, and a target framework of .NET Core 3.1, the following is generated for your original code:

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

Changing the target framework to .NET 5.0 (implicitly using the C# 9.0 standard) resolves the issue. (You may need to update your Visual Studio installation to have access to the .NET 5 framework build tools.)

like image 77
Adrian Mole Avatar answered Oct 22 '22 05:10

Adrian Mole


According to @juharr:

With C# 9 conditional operators are now target typed https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator

The documentation sent by him states the following:

Beginning with C# 9.0, conditional expressions are target-typed. That is, if a target type of a conditional expression is known, the types of consequent and alternative must be implicitly convertible to the target type, as the following example shows:

var rand = new Random();
var condition = rand.NextDouble() > 0.5;

int? x = condition ? 12 : null;

IEnumerable<int> xs = x is null ? new List<int>() { 0, 1 } : new int[] { 2, 3 };

That is exactly what I was looking for, thank you @juharr

like image 21
Marcelo Avatar answered Oct 22 '22 06:10

Marcelo