Click here to Skip to main content
Click here to Skip to main content

Tagged as

Execute lambda expression given as string

, 26 Jan 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
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;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Member 8583845

United States United States
No Biography provided

Comments and Discussions

 
Generalyou will also get a deprecated code warning using the compil... PinmemberGParkings13-Feb-12 0:57 
GeneralBe aware, however, that every time that you compile and load... PinmemberJuan__Perez30-Jan-12 11: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... PinmemberDean Oliver28-Jan-12 22:17 
GeneralReason for my vote of 5 funny idea - I used similar code for... Pinmemberjohannesnestler26-Jan-12 12:58 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411023.1 | Last Updated 26 Jan 2012
Article Copyright 2012 by Member 8583845
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid