Skip to content

Expression.Switch without a default case incorrectly calls first case for unmatched values. #428

@bfarmer67

Description

@bfarmer67

I found an issue with switch expressions that I wanted to report.

When Expression.Switch is created without a default case, the first case expression is being incorrectly called as a default.

   var number = Expression.Parameter(typeof(int), "number");
   var writeLineMethod = typeof(Console).GetMethod("WriteLine", new[] { typeof(string) });

   var switchExpr = Expression.Switch(
      number,
      new SwitchCase[]
      {
         Expression.SwitchCase( Expression.Call(null, writeLineMethod, Expression.Constant("Case 1")), Expression.Constant(1)),
         Expression.SwitchCase( Expression.Call(null, writeLineMethod, Expression.Constant("Case 2")), Expression.Constant(2))
      }
    );

    var lambda = Expression.Lambda<Action<int>>(switchExpr, number);
    var action = (Action<int>) lambda.CompileFast();

    action(3); // RETURNS "Case 1" - should do nothing.

If you explicitly pass Expression.Empty() for the default case, the switch behaves correctly.
If you pass null for the default case, you also see the error.

Here is a dotnetfiddle that reproduces the issue https://dotnetfiddle.net/7xKCTF

Thank you again for your library.

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions