Monday, June 4, 2012

Expression Trees II - Textual Representation

As we all know that C# does not support Eval Mechanism i.e. the capability of evaluating a language expression at runtime. The languages, which support this feature, can parse string representation of an expression. They can evaluate the expression and return the result.

Modern languages can vary in the strength of support of eval mechanism. The above is javascript code using eval. It not only supports language elements (Math.pow) but it also has used variables from outside the scope of expression (x & y) which is a very strong support of the mechanism. The above code would result value as 300.

In order to support the eval mechanism, a framework must support runtime parsing of expressions and generation of executable code based on this parsing. For interpreted languages, it is a very trivial task. Compiled languages can use JIT compilation support to provide similar features. C# does not support eval mechanism as in the above example as it does not support string based expressions. Expression Tree is closest to the eval mechanism as it allows us to be creating dynamic expression (at runtime). It then allows us to create executable code based on this expression, cache them and reuse them during the life time of the application.

In the previous post [http://www.shujaat.net/2012/05/expression-trees-part-i.html], we discussed how we can create delegate based on an expression. The delegate allows us to run the code represented by the source expression. On the other hand, Expression can also provide its textual representation. This can not only serve logging but we can also use it for UI consumption. Let's use one of the expression introduced in previous post and write it on the console.

This would result in the following output:


Although this seems very promising but it has limited support for more complex expressions including BlockExpression and LambdaExpression.


Zindabad!

No comments: