Skip to content

checked expression containing switch expression has no effect #61843

@gurustron

Description

@gurustron

Version Used: Latest

Steps to Reproduce:

From SO - using switch expression inside checked expression does not lead neither to exception nor to compilation error.

using System;
Int32 x = Int32.MaxValue;
Int32 y = Int32.MaxValue;

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

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

try
{
  Console.WriteLine($"{x} + {y} = {SomeFunc(x, y)}");
}
catch ( OverflowException ex )
{
  Console.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
  }
);

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

(A sharplab repro)

Expected Behavior:
Exception or compilation error

Actual Behavior:
Just works.

Metadata

Metadata

Assignees

Labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions