Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#
Tip/Trick

Execute lambda expression given as string

Rate me:
Please Sign up or sign in to vote.
4.85/5 (10 votes)
26 Jan 2012CPOL 49.7K   25   4
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalyou will also get a deprecated code warning using the compil... Pin
GParkings12-Feb-12 23:57
GParkings12-Feb-12 23:57 
GeneralBe aware, however, that every time that you compile and load... Pin
Juan__Perez30-Jan-12 10:06
professionalJuan__Perez30-Jan-12 10:06 
Be aware, however, that every time that you compile and load an assembly in this way, it gets loaded into memory and is never unloaded. Therefore, if you invoke the ExecuteLambdaExpression method repeatedly, it will slowly leak memory. One remedy is to create an AppDomain, load the assembly into the AppDomain, execute the method, and then unload the AppDomain.
GeneralReason for my vote of 5 Very cool idea. I give you 5 because... Pin
Dean Oliver28-Jan-12 21:17
Dean Oliver28-Jan-12 21:17 
GeneralReason for my vote of 5 funny idea - I used similar code for... Pin
johannesnestler26-Jan-12 11:58
johannesnestler26-Jan-12 11:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.