Search code examples
c#conditional-operatorlocal-functions

Can you use a ternary operator in a C# local function?


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 before C# 9.0 both the value on the left and the the value on the right of the colon have to be of the same type; therefore, you need to cast the non null value here. Starting with C# 9.0 the type can be infered from the target type.