Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Execute lambda expression given as string

0.00/5 (No votes)
26 Jan 2012 1  
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:


C#
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.


C#
delegate object MethodDelegate(params object[] args);

C#
//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;
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here