Expression.Switch without a default case incorrectly calls first case for unmatched values.
Closed this issue · 1 comments
bfarmer67 commented
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.
dadhi commented
@bfarmer67 Thanks for reporting and the example. I will check.