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);
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;
}
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.