October 13, 2010

Express Review of Expression Trees

Yesterday I spoke about the Expression Trees. I must admit that haven't practice with this pretty feature in C#3.0. But after several blogs and msdn info I can tell that this is powerful technology which allows us to create a dynamic scenarios in our programs. To work with expression trees user must has a basic knowlages of lambda expression and understand what is a tree. Calculations in the tree are moves from the leafs to the root of tree. Miscrosoft provides a 56 different actions to use in Expressions. There are Add, Bind, Block, Break, Call, Catch, Coalesce, Continue, Equal, GreaterThan, Lambda, Loop, New, Or , PowerAssign and other.. Expression class has a several derived class such as BinaryExpression, BlockExpression, ConditionalExpression, ConstantExpression, DynamicExpression and other, which separate expression by their type. It is necessary to say that every node in the tree is an expression. Digits or Strings are also expression, to be exact there is an Expression.Constant.
Everybody who works with expression trees must be very attentive. It's too lightly to make some mistake when constuct trees. For example if you write
Expression.Add( Expression.Constant( 2 ), Expression.Constant( 3 ) ); 
 it's correct and represent a (2+3) expression, but the next code will take a runtime exception "The binary operator Add is not defined for the types 'System.String' and 'System.String'."

Expression.Add( Expression.Constant( "ab" ), Expression.Constant( "cd" ) );
It's one of the many cases when successful compilation isn't a successfull execution of the program.
 
Expression trees
View more presentations from Yuriy Seniuk.

Good luck! Try yourself with expression!

No comments:

Post a Comment