Expression.SwitchCase with C# 7 pattern matching

Viewed 361

I want to dynamically build an Expression tree in C# that represents this code:

switch (x)
{
    case A1 cx: Handle(cx); break;
    case A2 cx: Handle(cx); break;
}

So far I have something like this:

Expression.Switch(xParameterExpression,
    Expression.SwitchCase(
        method1CallExpression, /* test value expression - what to put here ?? */),
    Expression.SwitchCase(
        method2CallExpression, /* test value expression - what to put here ?? */));

I could also use the Expression.TypeAs but it doesn't seem to work. I suspect I need an expression similar to the if (x is A1 cx) { } conditional rather than the var cx = x as A1;.

I realise these are new C# 7.0 features but wondered if all new language features are added to Expressions?

1 Answers

None of the C# 7.0 feature have support in expression trees at this point. You will find a number of compiler Pull Requests that explicitly handle this (produce a diagnostic if you tried).

If this is important to you, I'd suggest you file an issue on the Roslyn repo (I couldn't find an existing one) and gather some support.

Related