Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 4 "dynamic" in expression trees

I'm trying to figure out how to put all the pieces together, and would appreciate a concrete source code sample for a simple case to start with.

Consider the following C# code:

Func<int, int, int> f = (x, y) => x + y; 

I can produce an equivalent function at runtime using expression trees as follows:

var x = Expression.Parameter(typeof(int), "x"); var y = Expression.Parameter(typeof(int), "y"); Func<int, int, int> f =     Expression.Lambda<Func<int, int, int>>(         Expression.Add(x, y),         new[] { x, y }     ).Compile(); 

Now given the following lambda:

Func<dynamic, dynamic, dynamic> f = (x, y) => x + y; 

how would I generate the equivalent using expression trees (and, presumably, Expression.Dynamic)?

like image 257
Pavel Minaev Avatar asked Aug 25 '10 00:08

Pavel Minaev


1 Answers

You can create an expression tree that represents a dynamic C# addition expression by passing the CallSiteBinder for a dynamic C# addition expression into Expression.Dynamic. You can discover the code to create the Binder by running Reflector on the original dynamic expression. Your example would go something like this:

var x = Expression.Parameter(typeof(object), "x"); var y = Expression.Parameter(typeof(object), "y"); var binder = Binder.BinaryOperation(     CSharpBinderFlags.None, ExpressionType.Add, typeof(Program),     new CSharpArgumentInfo[] {          CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),          CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null)}); Func<dynamic, dynamic, dynamic> f =     Expression.Lambda<Func<object, object, object>>(         Expression.Dynamic(binder, typeof(object), x, y),         new[] { x, y }     ).Compile(); 
like image 103
Quartermeister Avatar answered Sep 21 '22 11:09

Quartermeister