Thursday, July 5, 2007

Creating Assembly Dynamically

public void CreateAssembly()
{
AppDomain AppDom = AppDomain.CurrentDomain;

// create a new dynamic assembly
AssemblyName AsmName= new AssemblyName();
AsmName.Name = "MyAssembly";
AssemblyBuilder AsmBuild = AppDom.DefineDynamicAssembly(
AsmName, AssemblyBuilderAccess.Run);

// create a new module to hold code in the assembly
ModuleBuilder ModBuild = AsmBuild.DefineDynamicModule("MyModule");

// create a type in the module
TypeBuilder TypeBuild = ModBuild.DefineType(
"MyClass", TypeAttributes.Public);

// create a method of the type
Type ReturnType = typeof(int);
Type[] ParamsType = new Type[0];
MethodBuilder MethBuild = TypeBuild.DefineMethod("MyMethod",
MethodAttributes.Public, ReturnType, ParamsType);

// generate the MSIL
ILGenerator Gen = MethBuild.GetILGenerator();
Gen.Emit(OpCodes.Ldc_I4, 1);
Gen.Emit(OpCodes.Ret);

//////////////////////////////////////////////////////////

// Now consume the type that is created above

Type TypeObj = TypeBuild.CreateType();

// create an instance of the new type
Object Obj = Activator.CreateInstance(TypeObj);
// create an empty arguments array
Object[] ObjArr = new Object[0];
// get the method and invoke it
MethodInfo MethInfo = TypeObj.GetMethod("MyMethod");
int RetVal = (int)MethInfo.Invoke(Obj, ObjArr);
MessageBox.Show("Method " + MethInfo + " in Class " + TypeObj + " returned " + RetVal);

}

Reference:
http://www.java2s.com/Code/CSharp/Development-Class/Illustratesruntimetypecreation.htm

No comments: