I've used it before to dynamically detour functions (getting rid of that XNA 4 Hi Profile checking shit), but I'm not sure of any other reasons I'd use it...
The primary functionality of this namespace is to provide runtime code generation services. Starting with .NET 2.0, services to emit code at runtime have been added to the framework. This is known as Lightweight code generation. The use of this API requires a thorough understanding of IL. But here's a simple example of how you can generate a run-time code:
[highlight=c#]using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
namespace LCGConsole
{
class Program
{
static void Main(string[] args)
{
//Create a runtime assembly that will not be saved to disk.
var Asm = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("MyAssembly"), AssemblyBuilderAccess.Run);
//Create a dynamic module.
var Module = Asm.DefineDynamicModule("MyModule");
//Create a type that will enclose our method.
var Type = Module.DefineType("MyClass");
//Create a static method which will perform some operation. Make it static and public so it can be accessed by the Main.
var Method = Type.DefineMethod("SimpleHelloWorld",MethodAttribu tes.Static | MethodAttributes.Public);
//Get MSIL Generator for our method.
var GenerateILCode = Method.GetILGenerator();
//Emit IL Code. In this case 'Ldstr' means LoadString. We load 'Hello World ;]' to the IL stack.
GenerateILCode.Emit(OpCodes.Ldstr, "Hello World ;]");
//Emit IL Code for calling the 'WriteLine' method using Console.
GenerateILCode.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new[] { typeof(string) }, null));
//Emit IL code to return the result of last call.
GenerateILCode.Emit(OpCodes.Ret);
//Create the type from our Dynamic Type Definition.
var Result = Type.CreateType();
//Finally, invoke the method with no parameters.
Result.GetMethod("SimpleHelloWorld").Invoke(null, null);
Console.ReadLine();
}
}
}[/highlight]
I've commented the code. Guess shouldn't be hard for you to understand.