var method = new CompilerAnonymousMethod("x", new[] { typeof(int) }, new[] { "return x + 1;" }); var storey = new AnonymousMethodStorey(); storey.Add(method);
var code = @" class MyClass { static void Main() { FuncThis code uses the CSharpCodeProvider class to create a new C# compiler and CompilerParameters class to specify that the compiled assembly should be generated in memory. The code is then compiled and the resulting assembly is used to retrieve the MethodInfo for the Main method of the MyClass class. Finally, that method is invoked to run the compiled code, which includes the anonymous method that takes an integer parameter and returns that integer plus one.func = x => { return x + 1; }; Console.WriteLine(func(5)); } }"; var provider = new Mono.CSharp.CSharpCodeProvider(); var parameters = new CompilerParameters() { GenerateInMemory = true }; var results = provider.CompileAssemblyFromSource(parameters, code); var assembly = results.CompiledAssembly; var type = assembly.GetType("MyClass"); var method = type.GetMethod("Main").Invoke(null, null);