Create Dynamic Copy of Existing Assembly/Module

2.4k Views Asked by At

Is it possible to create a dynamic copy of an assembly or module/class? I was able to easily find how to create a dynamic assembly or module from scratch using AssemblyBuilder/ModuleBuilder (as seen here), but is there a way to create a copy of an existing assembly or type as its respective Builder type?

Edit 1

For example, say you have a standard Console Application with the obligatory Program class and Main method and you add another class to the project, called 'A'. My goal is to create a dynamic copy of the A class within the Main method using ModuleBuilder or something like it.

Edit 2

The reason I want to make a copy of class A, is because I would like an exact duplicate of class A, including methods, fields, properties, etc., but created dynamically. What I don't want, is to have to manually create the type and all of its members (methods, fields, properties, etc.) using TypeBuilder/CodeDom, since, in some cases, I may not know all of the details about a class and its inner workings or the class may be large and tedious/impossible to reproduce using this method.

Hopefully some pseudocode can illustrate what I'm looking for:

// create AssemblyBuilder using the assembly of the A class so you end up with a
// dynamic copy of the assembly
AssemblyBuilder ab = new AssemblyBuilder(Assembly.GetAssembly(typeof(A)));

// get the Type as a TypeBuilder from the AssemblyBuilder
TypeBuilder tb = ab.GetModule("Test.exe").GetType(typeof(A).FullName);

I'd basically just like to box an Assembly as an AssemblyBuilder or Type as a TypeBuilder. I also don't need to be able to save the assembly.

1

There are 1 best solutions below

2
On

From your comments above, look like you would like generate code C# and can compile it as well. If so I suggest you should look at CodeDom instead of using AssemblyBuilder and ModuleBuilder. It will straight forward and easy to understand.

The links below will help you:

http://msdn.microsoft.com/en-us/library/650ax5cx.aspx

http://www.codeproject.com/Articles/7119/Compiling-with-CodeDom

http://blogs.msdn.com/b/davidebb/archive/2009/06/03/codedom-vs-t4-two-approaches-to-code-generation.aspx

BTW, if you would like to build a tool similar Reflector which will load outside assemblies and generate back to code then you should use CodeDom as well.

Take reference from here:

https://www.simple-talk.com/dotnet/.net-framework/-.net-reflector-meets-the-codedom/