Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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. 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading