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:
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.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With