I have a function which creates a delegate using expression trees. Within this expression I use a variable captured from multiple parameters passed in to the function. The actual expression tree is rather large so as an example:
Delegate GenerateFunction<T>(T current, IList<T> parents) {
var currentExpr = Expression.Parameter(typeof(T), "current");
var parentsExpr = Expression.Parameter(parents.getType(), "parents");
var parameters = new List<ParameterExpression>();
....
return Expression.Lambda(Expression.Block(new List<ParameterExpression> { parentsExpr, currentExpr }, ....), parameters.ToArray()).Compile();
}
I then invoke this method from another method before passing that function to another function to use. Once that's all done I want to access the content of parents which gets updated within the expression tree.
Everything seems to compile, and my expression looks ok, but when I run it I appear (although I can't really be sure) to be getting null reference exceptions when accessing the parents variable (inside the expression/closure).
I guess I'd like to know if I'm doing something wrong or whether this is possible as well as tips for understanding what's going on. I don't seem to be able to find any hoisted (?) local variables within the method so I'm wondering whether they're being captured at all?
Thanks, Mark