Create assembly : Assembly : Reflection C# Source Code


Custom Search

C# Source Code » Reflection » Assembly »

 

Create assembly









    


using System;
using System.Reflection;
using System.Reflection.Emit;

class CodeGenerator {       
    Type t;
    public static void Main() {
       CodeGenerator codeGen = new CodeGenerator();
       Type t = codeGen.T;

       if (t != null) {
          object o = Activator.CreateInstance(t);
          MethodInfo helloWorld = t.GetMethod("HelloWorld");
          if (helloWorld != null) {
             // Run the HelloWorld Method
             helloWorld.Invoke(o, null);
          } else {
             Console.WriteLine("Could not retrieve MethodInfo");
          }
       } else {
             Console.WriteLine("Could not access the Type");
       }
    } 
    public CodeGenerator() {
       AppDomain currentDomain = AppDomain.CurrentDomain;

       AssemblyName assemName = new AssemblyName();
       assemName.Name = "MyAssembly";

       AssemblyBuilder assemBuilder = currentDomain.DefineDynamicAssembly(assemName, AssemblyBuilderAccess.Run);

       ModuleBuilder moduleBuilder = assemBuilder.DefineDynamicModule("MyModule");

       TypeBuilder typeBuilder = moduleBuilder.DefineType("MyClass",TypeAttributes.Public);

       MethodBuilder methodBuilder = typeBuilder.DefineMethod("HelloWorld", MethodAttributes.Public,null,null);

       ILGenerator msilG = methodBuilder.GetILGenerator();
       msilG.EmitWriteLine("www.navioo.com");
       msilG.Emit(OpCodes.Ret);

       t = typeBuilder.CreateType();
   }
   public Type T {
       get { 
         return this.t;
       }
   }
}


           
       
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Reflection
» Assembly