Search code examples
c#anonymous-methodsexpressionbuilder

Replacing anonymous methods with expression tree


If I want to replace this anonymous method:

Func<int, int> f = delegate(int i)
{
     return i + 1;
};

with an expression tree, it would like this:

ParameterExpression i = Expression.Parameter(typeof(int), "i");
Expression one = Expression.Constant(1, typeof(int));
Expression body = Expression.Add(i, one);
Func<int, int> f = Expression.Lambda<Func<int, int>>(body, i).Compile();

(I know: an expression tree will secretly dynamically create another anymous method, but that is not the point).

Now I want to replace the following method with an expression tree:

Func<int, int> f = delegate(int i)
{
     Debug.WriteLine("Inside the function!");
     return i + 1;
};

Is there a way and how do I do this?


Solution

  • Yes, you can do the replacement. The structure of your current expression looks like this:

    Expression.Lambda
        Expression.Add
            Expression.Parameter("a")
            Expression.Constant(1)
    

    the structure of the new expression will look like this:

    Expression.Lambda
        Expression.BlockExpression
            Expression.Call
                Expression.Constant("Inside the function!")
                MedhodInfo(Debug.WriteLine)
            Expression.Add
                Expression.Parameter("a")
                Expression.Constant(1)
    

    You will need to provide MedhodInfo for the Debug.WriteLine to the Call expression. The last expression in the block (i.e. a+1) will be considered block's return expression.