What are the differences between Expression trees and CodeDom?
Which should I use for which scenario?
What are the differences between Expression trees and CodeDom? Which should I use for
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Expression trees have a lot in common with (for example) an AST. It doesn’t map directly to code, but is very amenable to construction from algorithms. For example, if you are parsing a formula:
that is:
In fact, I have done exactly this, using a parser that build an object tree, with objects generating the complete expresion via a “visitor” implementation. In .NET 4.0, the richer expression-tree support makes it possible to support most scenarios, and compile it on demand.
Another key use of expressions is that you can deconstruct them at runtime, so in your code you might have:
and extract the
SomeMethodmethod-info,1and"abc"etc.codedom maps to code. It is all about statements etc, very similar to how you would write regular code. The most common use of codedom is for code generation, as part of tooling. You can use it for dynamic compilation, but to be honest it is harder. I am not a fan. The nice feature is that a codedom tree might work for multiple languages.
Another contender here should be
DynamicMethodand/orILGenerator. This doesn’t map to an AST (expression), and can’t be used to generate source-code (codedom), but allows full access to the MSIL tools. Of course, it also requires that you think in terms of stacks etc, but it is very efficient and effective for meta-programming.If
ILGeneratoris too hard-core, and codedom is a PITA, then another option is runtime generation of code as a string. Then pass that throughCSharpCodeProviderto compile it. There are parts of the core runtime that do this (XmlSerializerIIRC).So to summarise:
ILGeneratororCSharpCodeProvider; alsoExpressionin 4.0 (but this is quite limited in 3.5)ExpressionExpression