How to create custom System.Linq.Expression classes in C#?

c# expression-trees

Question

Is it possible to create custom Expression classes? If so, does anyone have any examples? Inheriting from the framework abstract Expression class poses a problem in that its constructor takes an ExpressionType parameter, which is a framework enum type - I obviously cannot customise this!

Any ideas?

Expert Answer

This is exactly what the DLR code on codeplex had to do; in the end, they re-created the entire codebase in a different namespace (IIRC), until 4.0 gets shipped.

This doesn't necessarily play nicely with the C# compiler; I honestly haven't tried.


Popular Answer

With .net 3.5 you can't do this because the Expression constructor takes in an ExpressionType enum value, and you can't add new node types to the enum.

You can't overload an existing node type either, because you can't inherit from any of the "leaf classes" (like BinaryExpression) because they are all sealed.

According to the MSDN docs it looks like you can do this in CLR v4, as long as you override the "Reduce" method and use a node type ExpressionType.Extension.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why