Search code examples
c#anonymous-methods

Create anonymous method from a string in c#


is it possible to create an anonymous method in c# from a string?

e.g. if I have a string "x + y * z" is it possible to turn this into some sort of method/lambda object that I can call with arbitrary x,y,z parameters?


Solution

  • It's possible, yes. You have to parse the string and, for example, compile a delegate using expression trees.

    Here's an example of creating (x, y, z) => x + y * z using expression trees:

    ParameterExpression parameterX = Expression.Parameter(typeof(int), "x");
    ParameterExpression parameterY = Expression.Parameter(typeof(int), "y");
    ParameterExpression parameterZ = Expression.Parameter(typeof(int), "z");
    Expression multiplyYZ = Expression.Multiply(parameterY, parameterZ);
    Expression addXMultiplyYZ = Expression.Add(parameterX, multiplyYZ);
    Func<int,int,int,int> f = Expression.Lambda<Func<int, int, int, int>>
    (
        addXMultiplyYZ,
        parameterX,
        parameterY,
        parameterZ
    ).Compile();
    Console.WriteLine(f(24, 6, 3)); // prints 42 to the console