2

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?

Old Skull
  • 165
  • 7
  • 1
    This seems like a bug to me, I would advise you to post this on the proper Github page as an issue and see what the response is. I am not entirely sure what the right project is though. – Lasse V. Karlsen Jun 13 '22 at 09:00
  • Created a [github](https://github.com/dotnet/roslyn/issues/61843) issue (though possibly should be runtime, not compiler). Looks like a bug to me. – Guru Stron Jun 13 '22 at 09:56

1 Answers1

2

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().

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276