System.Reflection.Emit contains classes such as AssemblyBuilder , ModuleBuilder , TypeBuilder , and MethodBuilder which are used to create new types during runtime. Rarely used in conventional programming, the ability to create new Type s during runtime may be useful when you want to dynamically create new proxy classes for remote operations. Since this is an advanced topic, I will give only a simple code example to give a clue as to which classes to use. Refer to the API documentation for more information about each class in System.Reflection.Emit . 1: using System; 2: using System.Reflection; 3: using System.Reflection.Emit; 4: 5: public class TestClass{ 6: 7: public static Type CreateType (){ 8: 9: AppDomain ad; 10: AssemblyName an; 11: AssemblyBuilder ab; 12: ModuleBuilder mb; 13: TypeBuilder tb; 14: MethodBuilder methb; 15: ILGenerator ilg; 16: 17: // AppDomain.CurrentDomain returns the current process 18: // that is running 19: ad = AppDomain.CurrentDomain; 20: 21: // create a new assemby called 'MyAssembly' 22: an = new AssemblyName(); 23: an.Name = "MyAssembly"; 24: ab = ad.DefineDynamicAssembly 25: (an, AssemblyBuilderAccess.Run); 26: 27: // create a new module called 'MyModule' 28: mb = ab.DefineDynamicModule("MyModule"); 29: 30: // create new Type called 'MyType' 31: tb = mb.DefineType("MyType", TypeAttributes.Public); 32: 33: // create new method called DoThis which takes in no 34: // parameters and is public. 35: methb = tb.DefineMethod 36: ("DoThis", MethodAttributes.Public, null, null); 37: 38: // Generate IL codes for DoThis method. 39: // All DoThis does is to print out a string and return. 40: ilg = methb.GetILGenerator(); 41: ilg.EmitWriteLine("i love computers!"); 42: ilg.Emit(OpCodes.Ret); 43: 44: // complete creating the Type. Call tb.CreateType only 45: // after all the members within have been defined. 46: return tb.CreateType(); 47: } 48: 49: public static void Main(){ 50: // CreateType returns a dynamically generated Type 51: Type t = CreateType(); 52: 53: // create new instance of the dynamically generated type 54: object o = Activator.CreateInstance(t); 55: 56: // retrieve and invoke the DoThis method of the object 57: MethodInfo m = t.GetMethod("DoThis"); 58: m.Invoke(o, null); 59: } 60: } Output: c:\expt>test i love computers! The action happens in the CreateType method. When CreateType runs, it dynamically creates an assembly ( MyAssembly ) (lines 22 “ 25) which contains a module ( MyModule ) (line 28), which in turn contains a new Type ( MyType ) (line 31). MyType contains a single method ( DoThis ) which returns void and takes in no parameters (lines 35 “ 42). All DoThis does is print out a string and return (coded in lines 41 “ 42). Reflection is also used extensively together with custom attributes to retrieve attribute values during runtime from an entity. Custom attributes are covered in Chapter 28. |