Here is what I would like to implement:
public static void foo()
{
// Local function
int? parseAppliedAmountTernary( decimal? d ) {
d.HasValue ? return Convert.ToInt32( Math.Round(d.Value, 0) ) : return null;
}
// The rest of foo...
}
However, I get a compilation error. Is this syntax even possible? I am using Visual Studio 2019, .NET Framework 4, which (currently) equates to C# 7.3.
Note – I am just trying to figure out the syntax… any philosophical discussion regarding the "readability" of the code or other aesthetics, while interesting, are beside the point. 🙂
Code sample (uses Roslyn 4.0)
https://dotnetfiddle.net/TlDY9c
>Solution :
The ternary operator is not a condition but an expression which evaluates to a single value. It is this value that you have to return:
return d.HasValue ? (int?)Convert.ToInt32(Math.Round(d.Value, 0)) : null;
Note, that both values to the left and the right of the colon have to be the of the same type; therefore, you need to cast the non null value here.