.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Sandeep Singh

Home >> Code Snippets >> Javascript >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

How to create Dynamic Assembly : a practical scenario

Posted By:Gaurav Arora       Posted Date: April 28, 2009    Points: 10    Category: Javascript    URL: http://www.dotnetspark.com  

The following code snippet showed how to create a dynamic assembly: 

/* This Example is a part of different
* examples shown in Book:
* C#2005 Beginners: A Step Ahead
* Written by: Gaurav Arora

// File name : dynamicAssembly.cs
//This demostrates how to build a dynamic assembly

using System;
using System.Reflection;
using System.Reflection.Emit;
namespace CSharp.AStepAhead.dynamicAssembly
class CodeGenerator
Type t;
AppDomain currentDomain;
AssemblyName assemName;
AssemblyBuilder assemBuilder;
ModuleBuilder moduleBuilder;
TypeBuilder typeBuilder;
MethodBuilder methodBuilder;
ILGenerator msilG;

public static void Main()
CodeGenerator codeGen = new CodeGenerator();
Type myType = codeGen.T;
if (myType != null)
object o = Activator.CreateInstance(myType);
MethodInfo helloWorld = myType.GetMethod("HelloWorld");
if (helloWorld != null)
// Run the HelloWorld Method
helloWorld.Invoke(o, null);
else //if method info null
Console.WriteLine("Could not retrieve MethodInfo");
else //if type null
Console.WriteLine("Could not access the Type");

public CodeGenerator()
// Get the current Application Domain.
// This is needed when building code.
currentDomain = AppDomain.CurrentDomain;

// Create a new Assembly for Methods
assemName = new AssemblyName();
assemName.Name = "dynamicAssembly";
assemBuilder = currentDomain.DefineDynamicAssembly(assemName, AssemblyBuilderAccess.Run);

// Create a new module within this assembly
moduleBuilder = assemBuilder.DefineDynamicModule("dynamicAssemblyModule");

// Create a new type within the module
typeBuilder = moduleBuilder.DefineType("dynamicAssemblyClass", TypeAttributes.Public);

// Now add the HelloWorld method to the class that was just created.
methodBuilder = typeBuilder.DefineMethod("HelloWorld", MethodAttributes.Public, null, null);

// Now generate some Microsoft Intermediate Language Code that simply
// writes a line of text out to the console.
msilG = methodBuilder.GetILGenerator();
msilG.EmitWriteLine("Hello! This is a dynamic assembly.");

// Create a type.
t = typeBuilder.CreateType();

public Type T
return this.t;

Anyone can create a dynamic assembly using System.Reflection.Emit. 


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend