I'm honestly just lost, I can't seem to make sense of how Expression tree syntax is supposed to function, and keep getting errors trying to create the simplest of lambdas.
Let's take a very basic function: you supply a number as a parameter, and it simply adds that to 0, yes it useless, but I can't even make that work:
public void AddNumber(int number)
{
var input = Expression.Parameter(typeof(int), "number");
var result = Expression.Variable(typeof(int), "result");
var addAssign = Expression.AddAssign(result, input);
int myExpectedResult = Expression.Lambda<Func<int, int>>(addAssign, input).Compile()(number);
}
I get an error because the variable result is created, but not defined, which makes sense. So I assume I need to assign some value to it to make it work:
public void AddNumber(int number)
{
var input = Expression.Parameter(typeof(int), "number");
var result = Expression.Variable(typeof(int), "result");
var addAssign = Expression.AddAssign(result, input);
int myExpectedResult = Expression.Lambda<Func<int, int>>(addAssign, input).Compile()(number);
}
Same error, I'm assuming because the assign isn't really taken into account as it is not used. But you also can't use that assign variable as a parameter for the AddAssign function, so it basically makes no difference.
Now, if I create a block expression to do both assignements in a row, this will get rid of the error, however, my "input" is now always set to 0:
public void AddNumber(int number)
{
var input = Expression.Parameter(typeof(int), "number");
var result = Expression.Variable(typeof(int), "result");
var blockExpression = Expression.Block(new[] { input, result },
Expression.Assign(result, Expression.Constant(0)),
Expression.AddAssign(result, input));
int myExpectedResult = Expression.Lambda<Func<int, int>>(blockExpression, input).Compile()(number);
}
How are you actually supposed to simply add a parameter, create a variable, then assign a value to that variable to return it? I can't seem to find any tutorial that properly explains how to keep the link between parameters/variables, in different BlockExpressions.
Thanks a lot! Any help is appreciated!