Mega Code Archive

 
Categories / C# / Reflection
 

Illustrates runtime type creation

/* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110 */ /*   Example17_7 illustrates runtime type creation */ using System; using System.Reflection; using System.Reflection.Emit; public class Example17_7  {     public static void Main()      {         // get the current appdomain         AppDomain ad = AppDomain.CurrentDomain;         // create a new dynamic assembly         AssemblyName an = new AssemblyName();         an.Name = "DynamicRandomAssembly";         AssemblyBuilder ab = ad.DefineDynamicAssembly(          an, AssemblyBuilderAccess.Run);         // create a new module to hold code in the assembly         ModuleBuilder mb = ab.DefineDynamicModule("RandomModule");         // create a type in the module         TypeBuilder tb = mb.DefineType(          "DynamicRandomClass",TypeAttributes.Public);         // create a method of the type         Type returntype = typeof(int);         Type[] paramstype = new Type[0];         MethodBuilder methb=tb.DefineMethod("DynamicRandomMethod",           MethodAttributes.Public, returntype, paramstype);         // generate the MSIL         ILGenerator gen = methb.GetILGenerator();         gen.Emit(OpCodes.Ldc_I4, 1);         gen.Emit(OpCodes.Ret);         // finish creating the type and make it available         Type t = tb.CreateType();         // create an instance of the new type         Object o = Activator.CreateInstance(t);         // create an empty arguments array         Object[] aa = new Object[0];         // get the method and invoke it         MethodInfo m = t.GetMethod("DynamicRandomMethod");         int i = (int) m.Invoke(o, aa);         Console.WriteLine("Method {0} in Class {1} returned {2}",             m, t, i);     } } //============================================================= using System; public class DynamicRandomClass {     public int DynamicRandomMethod()     {         return 1;     } }