Project Description
The Polymorph Framework is a high level code generation framework for generating MSIL directly. Nearly any project using .Net Reflection can benefit in some way by using the Polymorph Framework.

The Polymorph Framework is a fork of the project Mono.CodeGeneration. The original codebase hasn't been worked on in a long time and wasn't getting much exposure to .Net and Mono developers so I have brought the project to CodePlex. The Polymorph Framework contains bug fixes, enhancements and every developers best friend, documentation!

The generation of MSIL directly permits developers to bypass language limitations. For example: The concept of private/public/protected are not strictly enforced by the CLR, they are only enforced by the compiler. So by generating MSIL directly you can create code that will read or write data to private members of a class. Imagine the possibilities of code writing code that is just as fast as code you could write at compile time with unlimited access, but at runtime.

MSIL? Sounds difficult, but this library makes it simple. Here is an example of how to generate code for a method that will add two numbers provided and return the result.

/* Create an instance of a DynamicMethod high level wrapper */
CodeDynamicMethod method = new CodeDynamicMethod("AddNumbers", typeof(int), 
     new Type[] { typeof(int), typeof(int) }, true);
/* Grab the method's code builder */
CodeBuilder cb = method.CodeBuilder;
/* This will generate the return statement that will add the first and second method arguments. */
cb.Return(method.GetArg(0) + method.GetArg(1));
/* Perform the method generation which will return a DynamicMethod and call it */
DynamicMethod dm = method.Generate();
object res = dm.Invoke(null, new object[] { 2, 3 });
Console.WriteLine("Result: " + res);

While you shouldn't need to touch IL with this framework, if you do plan to do any debugging of the internals of the framework, I would highly suggest you first download the following debugging visualizer Here.

Last edited Jan 26, 2009 at 2:11 AM by NickDarnell, version 11