The code shown in Listing 1 is to create an assembly
programmatically. The code written is written in the C# language. The purpose
of the code is to create an assembly with a class added to it. We also add a
method to the class and finally save the dynamic assembly to the local system.
Listing 1
AppDomain currentDomain = Thread.GetDomain();
AssemblyName myAssemblyName = new AssemblyName();
myAssemblyName.Name = "Test";
myAssemblyName.Version = new Version(1, 0, 0, 0);
AssemblyBuilder builder = currentDomain.DefineDynamicAssembly(myAssemblyName,
AssemblyBuilderAccess.RunAndSave);
ModuleBuilder ObjModuleBuilder = builder.DefineDynamicModule("MyModule");
ObjModuleBuilder.DefineType("ClassName",
TypeAttributes.Class).DefineMethod("MethodName",
MethodAttributes.Public, CallingConventions.Standard);
builder.Save("MyAssembly.dll");
The AssemblyBuilder class is completely responsible for the
creation of an assembly. An instance of the AssemblyBuilder class can be
created by the current AppDomain. The steps for creating the assembly are
listed below.
Step 1: Get the current application domain from the current thread.
Step 2: Create an object of the type AssemblyBuilder from
the current application domain.
Step 3: Create the module builder object from the
AssemblyBuilder.
Step 4: Create the different types, methods, etc. and add them
to the Module Builder.
Step 5: Save the builder to the local system.
The complete description of each and every class used is
illustrated in the next section.