How will u load dynamic assembly? How will create assemblies
at run time?



How will u load dynamic assembly? How will create assemblies at run time?..

Answer / ruena

You can create an assembly at runtime in the following
way...

The following example creates an assebly, class within it
and also defines the main method.

You can use dynamic invocation methods to execute the
assembly.

Make use of System.Reflection and System.Reflection.Emit
namespaces. Hope you find this useful.

public static void Main()
{
// 1.
// Create a new dynamic assembly
AssemblyName assemblyName = new AssemblyName
("DynamicHelloWorld");
AssemblyBuilder dynamicAssembly =
AppDomain.CurrentDomain.DefineDynamicAssembly(
assemblyName,

AssemblyBuilderAccess.RunAndSave);

// 2.
// Create a module inside the assembly
ModuleBuilder dynamicModule =
dynamicAssembly.DefineDynamicModule(

assemblyName.Name,
"DynamicHelloWorld
.exe");

//3.
// Create a type inside the module
TypeBuilder programType =
dynamicModule.DefineType(
"DynamicHelloWorld.Pro
gram",
TypeAttributes.Class
| TypeAttributes.Public);

// 4.
// Add a method
MethodBuilder main = programType.DefineMethod(
"Main",
MethodAttributes.Public |
MethodAttributes.Static,
null,
null);

// 5.
// Add the IL for the method. The IL is
equivalent to
// Console.WriteLine("Hello, world!");
Type console = typeof(Console);
MethodInfo writeLine = console.GetMethod(
"WriteLine",
new Type[] { typeof
(string) });

ILGenerator il = main.GetILGenerator();
il.Emit(OpCodes.Ldstr, "Hello, world!");
il.Emit(OpCodes.Call, writeLine);

// 6.
// Set the return value to 0
//il.Emit(OpCodes.Ldc_I4_0);
//il.Emit(OpCodes.Ret);

// 7.
// Now we're done, materialize the type
programType.CreateType();

// 8.
// Set the program's entry point to the Main
method
dynamicAssembly.SetEntryPoint(main,
PEFileKinds.ConsoleApplication);

// 9.
// Save the assembly
dynamicAssembly.Save("DynamicHelloWorld.exe");

Console.Write("Dynamic Assembly Emitted...");
}

Is This Answer Correct ?    4 Yes 0 No

Post New Answer

More Dot Net General Interview Questions

What is il in vb.net?

0 Answers  


Is .net a programming language?

0 Answers  


What is the difference between task and thread in .net?

0 Answers  


How to get the hostname or IP address of the server?

2 Answers  


Can a try block have more than one catch block?

0 Answers  






Explain difference between panel and groupbox classes using .net?

0 Answers  


What are the different types of remote object creation mode in .net?

0 Answers  


Will it go to finally block if there is no exception happened?

0 Answers  


What?s SingleCall activation mode used for?

1 Answers  


How can we convert XML data into DataBase table IN .Net?

3 Answers   Indus Media, Wipro,


What is shared and repeatable inheritance?

0 Answers  


Can u explain me What is encapsulation?

7 Answers   Deloitte, GK companies,


Categories