views:

707

answers:

4

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?

A: 

I don't believe you can extend Expression, but I think you could add in a couple of your extension methods to create expression trees to simplify the generation.

For example, maybe you always like to compare 2 strings so you could add an extension method that would return the tree to do the comparison. You can also add an expression that calls a function elsewhere in your code so you could only write expression trees for stuff that absolutely has to be developed that way.

Jake Pearson
+1  A: 

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.

Marc Gravell
Thanks Marc. Am i right in thinking that the DLR code will replace Linq expressions as the expression library of choice when c#4.0 ships?
MalcomTucker
+1  A: 

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.

Scott Wisniewski
A: 

I haven't tried this myself either, but I agree with Scott's statement that this should work in 4.0.

Specifically, the Expression Tree Spec on CodePlex says this about the NodeType property:

Derivations of Expression that are not in the common set of nodes in .NET should return node kind Extension

kreinsch