Skip to content

Instantly share code, notes, and snippets.

@ialex32x
Last active December 17, 2015 00:49
Show Gist options
  • Save ialex32x/5523557 to your computer and use it in GitHub Desktop.
Save ialex32x/5523557 to your computer and use it in GitHub Desktop.
C# compiler
using System;
namespace Sample
{
class Test
{
public static System.Reflection.Assembly Compile(string source)
{
var p = new Microsoft.CSharp.CSharpCodeProvider();
var c = p.CreateCompiler();
var parameters = new System.CodeDom.Compiler.CompilerParameters();
parameters.GenerateExecutable = false;
var r = c.CompileAssemblyFromSource(parameters, string.Format(
"using System; namespace Foo {{ public static class MethodStub {{ public static void foo() {{ {0} }} }} }}",
source));
return r.CompiledAssembly;
}
public static void Call(System.Reflection.Assembly a, string method)
{
var t = a.GetType("Foo.MethodStub");
t.InvokeMember(method,
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod,
System.Type.DefaultBinder, null, null);
}
[STAThread]
static void Main(string[] args)
{
var a1 = Compile("Console.WriteLine(\"Hello, Earth\");");
var a2 = Compile("Console.WriteLine(\"Hello, Moon\");");
Call(a2, "foo");
Call(a1, "foo");
System.Console.ReadKey(true);
}
}
}
@ialex32x
Copy link
Author

ialex32x commented May 6, 2013

        var p1 = Expression.Parameter(typeof(int));
        var c1 = Expression.Constant(13);
        var add = Expression.Add(p1, c1);

        var lambda = Expression.Lambda(add, p1);

        var d = lambda.Compile();

        Console.WriteLine(d.DynamicInvoke(10));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment