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
?