I implement simple examples using DLR. I showed how to create and evaluate expressions. Every Expression has some exposed properties and methods:
Note that each Expression object has an NodeType, and separated Type. Let explore that values:
BinaryExpression expr = Expression.Add(Expression.Constant(10), Expression.Constant(20)); Console.WriteLine(expr.GetType().FullName); Console.WriteLine(expr.Type); Console.WriteLine(expr.Left.Type); Console.WriteLine(expr.Right.Type); Console.WriteLine(expr.NodeType); Console.WriteLine(expr.Left.NodeType); Console.WriteLine(expr.Right.NodeType);
This is the first time I wrote an Expression.Add. This is a binary expression. Every binary expression has to leafs:
The output of the above code:
Note that the .GetType() (the .NET type) of the created Expression, is SimpleBinaryExpression: it’s not only an Expression object. But there is no AddExpression in DLR. The expr.NodeType exposes that the created expression is an Add one. DLR creators decided not to write a dedicated class for Expression.Add.
The BinaryExpression has a Type: System.Int32, an integer. This is the type that indicates what is the type of the returned value. It is derived from the types of the left and right part of the binary expression.
As in C#, we can combine binary expressions:// double result = (3d + 2d) / 7d; // Console.WriteLine(result); BinaryExpression expr2 = Expression.Divide( Expression.Add(Expression.Constant(3d), Expression.Constant(2d)), Expression.Constant(7d) ); Func<double> binaryDelegate = Expression.Lambda<Func<double>>(expr2).Compile(); Console.WriteLine(binaryDelegate.Invoke());
Next steps: IfThenElse expressions, switch expression, what is a Visitor? and a Reduce?.
Angel “Java” Lopez