Search code examples
c#exceptionswitch-statementcheckedexpression-body

C#: How to declare a checked switch-expression-bodied function?


I'm stuyding C# (10.0/.NET6) and I've got a question. There is a code:

Int32 x = Int32.MaxValue;
Int32 y = Int32.MaxValue;

try
{
  WriteLine($"{x} * {y} = {SomeFuncSwitch(x, y, 2)}");
  WriteLine($"{x} + {y} = {SomeFunc(x, y)}");
}
catch ( OverflowException ex )
{
  WriteLine( $"Overflow in {ex.TargetSite}!" );
}

static Int32 SomeFunc(Int32 x, Int32 y) => checked (x + y);

static Int32 SomeFuncSwitch(Int32 x, Int32 y, UInt16 condition) =>
checked (
  condition switch
  {
    1 => x + y,
    _ => x * y
  }
);

SomeFunc() throws exception, whereas SomeFuncSwitch() does not. It will if every switch case is checked. Is there a (proper) way to use single checked?


Solution

  • This appears to be a consequence of the use of a checked expression with a switch expression.

    If you do it like this (via a checked block), it works as expected:

    static Int32 SomeFuncSwitch(Int32 x, Int32 y, UInt16 condition)
    {
        checked
        {
            return condition switch
            {
                1 => x + y,
                _ => x * y
            };
        }
    }
    

    Like you, I would have expected the original code to work. Possibly there is some bug in the way the code is generated.

    It certainly looks like a compiler bug. If you look at the decompiled C# code you can see that the checked expression is missing from SomeFuncSwitch() but it is not missing from SomeFunc().