65.9K
CodeProject is changing. Read more.
Home

Execute lambda expression given as string

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.85/5 (10 votes)

Jan 26, 2012

CPOL
viewsIcon

51192

How to execute lambda expression given as string

Introduction

This code snippet enables you to read a lambda expression e.g. out of a database or a configuration file and executes it.

Using the code

You can use the code like this:

ExecuteLambdaExpression("int i = 5; MethodDelegate del = () => { 
       int j = 10; return j > i; }; bool val = del(); return val;"); 

If you want to use a Delegate with parameters, you should add another delegate to the "LambdaClass" given as string.

Modification

In a next version of this code, you can specify more delegates to be more flexible, or maybe a delegate with a parameter list.

delegate object MethodDelegate(params object[] args);
//ExecuteLambdaExpression("int i = 5;MethodDelegate del = () => {
//              int j = 10; return j > i; };bool val = del(); return val;")
private object ExecuteLambdaExpression(string lambdaExpression)
{
    string source =
    "namespace LambdaNamespace" +
    "{" +
        "public class LambdaClass" +
        "{" +
            "delegate bool MethodDelegate();" +
            "public bool LambdaMethod()" +
            "{" +
                lambdaExpression +
            "}" +
        "}" +
    "}";

    CompilerParameters parameters = new CompilerParameters();
    parameters.GenerateExecutable = false;
    CSharpCodeProvider codeProvider = new CSharpCodeProvider();
    ICodeCompiler icc = codeProvider.CreateCompiler();
    CompilerResults results = icc.CompileAssemblyFromSource(parameters, source);

    Console.WriteLine("compiled with errors: " + 
        results.Errors.HasErrors + ", warnings: " + 
        results.Errors.HasWarnings);

    if (!results.Errors.HasErrors && !results.Errors.HasWarnings)
    {
        Assembly ass = results.CompiledAssembly;

        object lambdaClassInstance = 
                ass.CreateInstance("LambdaNamespace.LambdaClass");

        object lambdaMethodResult = 
                lambdaClassInstance.GetType().InvokeMember("LambdaMethod", 
                BindingFlags.InvokeMethod, null, lambdaClassInstance, new object[] { });

        return lambdaMethodResult;
    }

    return null;
}