Have you ever generated code at runtime using Reflection.Emit()? Neither have I. It’s very complicated and I haven’t had a compelling-enough reason to attempt it. A developer by the name of Stefan Simek has created a brilliant API called RunSharp (or Run#) which wraps the native C# Emit() functionality with an infinitely easier to use facade.

Let’s say you want to generate a class with a single public method. At design time this is easy enough:

public class MyClass
public void Main(string[] args)
// do stuff

I’m not going to post what it would have been like using out-of-the-box reflection in C#, but let’s assume that it is the giant pain in the ass that it really is. Now here’s the Run# version:

AssemblyGen ag = new AssemblyGen(“MyExecutable.exe”);
TypeGen myClass = ag.Public.Class(“MyClass”);
CodeGen g = myClass.Public.Method(typeof(void), “Main”, typeof(string[]));
Operand args = g.Arg(0, “args”);
g.WriteLine(“// do stuff”);

Share this post: digg it | Email it |