rendered paste body// HelloWorld... the HARD way!
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection.Emit;
using System.Reflection;
namespace DynamicAssemblyDemo
{
class Program
{
static void Main(string[] args)
{
// Define the dynamic assembly
AssemblyName name = new AssemblyName("MyTempAssembly");
name.Version = new Version("1.0.0.0");
AppDomain currentAppDomain = AppDomain.CurrentDomain;
AssemblyBuilder tempAssembly =
currentAppDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
// Define the module
ModuleBuilder tempModule = tempAssembly.DefineDynamicModule("MyTempAssembly.dll");
TypeBuilder tempType = tempModule.DefineType("TempType", TypeAttributes.Public);
// Define the SayHello static method
MethodAttributes publicStatic = MethodAttributes.Public | MethodAttributes.Static;
MethodBuilder sayHelloMethod = tempType.DefineMethod("SayHello",
publicStatic, typeof(void), Type.EmptyTypes);
// Get method info for Console.WriteLine(String) and Console.Read()
string path = @"C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll";
Assembly mscorlib = Assembly.LoadFile(path);
Type consoleType = mscorlib.GetType("System.Console");
MethodInfo writeLineMethod = consoleType.GetMethod("WriteLine", new Type[] { typeof(string) });
MethodInfo readMethod = consoleType.GetMethod("Read", Type.EmptyTypes);
// Create the method body
ILGenerator sayHelloCodeGen = sayHelloMethod.GetILGenerator();
sayHelloCodeGen.Emit(OpCodes.Ldstr, "Hello World!");
sayHelloCodeGen.EmitCall(OpCodes.Call, writeLineMethod, null);
sayHelloCodeGen.Emit(OpCodes.Nop);
sayHelloCodeGen.EmitCall(OpCodes.Call, readMethod, null);
sayHelloCodeGen.Emit(OpCodes.Pop);
sayHelloCodeGen.Emit(OpCodes.Ret);
// Call the dynamically created SayHello method
Type newType = tempType.CreateType();
MethodInfo sayHello = newType.GetMethod("SayHello", Type.EmptyTypes);
sayHello.Invoke(null, new object[] { });
}
}
}