Question

Given some expression tree inner, I want to wrap it inside no-op expression of type void. Expression inner should still be evaluated, but its return type should be thrown away. How do I do it?

If you are curious as to why I would want to do it, one possible application for such casting is Expression.Switch, which requires all Expression.SwitchCase expressions to return the same type.

My current workaround is to cast everything to type Object by wrapping inner like this: Expression.Block(inner, Expression.Constant(null)). Such solution seems weird, bulks up my code, and possibly complicates the generated MSIL code too.

Was it helpful?

Solution

One option is to use the overload of Expression.Switch() that lets you specify the return type. If you specify void, then expressions of any type will be accepted as the cases. In this overload, you also need to specify the defaultBody and comparison parameters, but you can just make them null.

Another option is indeed to use Expression.Block(), but again the overload that lets you specify the type. In your case, that would be something like:

Expression.Block(typeof(void), inner)

I don't expect this to have any significant effect on the generated IL.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top