I have the following code :
var factory = Expression.Parameter(typeof(FooFactory));
var fooInstance = Expression.Variable(typeof(Foo));
var factoryCall = Expression.Call(factory, "Instantiate", new[] { typeof(Foo) });
Expression.Assign(fooInstance, factoryCall);
List<Expression> expressions = new List<Expression>();
// TODO : add more expressions to do things on fooInstance ...//
expressions.Add(fooInstance); //return fooInstance
Expression finalExpr = Expression.Block(new[] { fooInstance }, expressions);
What it is supposed to do :
Instantiate<T>()
method on it.The problem is : when I compile and call the expression, Instantiate() is never called. The value returned is always null :
var method = Expression.Lambda<Func<FooFactory, Foo>>(finalExpr, factory).Compile();
Foo foo = method(new FooFactory()); //foo is null :(
My bad. I forget that Expression.Assign()
returns an expression.
When doing this instead, it works beautifully :
List<Expression> expressions = new List<Expression>();
expressions.Add(Expression.Assign(fooInstance, call));
Thanks Luaan for the tip.