Is there a straightforward way to copy a Type using reflection?

I realize this is a very strange question. Let me just say that I have my reasons. (I tend to write very long, wordy questions; I want to keep this one short.)

If I have some type T, can I use reflection to define a new type, let's call it T2, that will basically be identical to T? What I'm looking for is essentially a dynamic way to do the equivalent of what would result if I wrote the exact same code (except for class name) in two separate source code files and compiled both.


I don't think there's a magic bullet method that will do your work for you, but you can do it with Reflection Emit.

Here's a nice tutorial on parts of the subject. Start there then move up to some of the sister articles.

Randolpho's links should point you in the right direction. As for emitting identical functionality, you can retrieve the IL from methods by calling X.GetMethodBody().GetILAsByteArray() where X is a given instance of MethodInfo. That would still need to be translated and re-emitted in your new method, though, because as far as I know there isn't a direct way to write an IL stream of byte[] to a particular ILGenerator as IL.

Haibo Luo had a blog post about this from 2005 that may point you in the right direction for translation (I haven't tried it out so I can't verify that it works).

You can copy structure of type relying on System.Reflection.Emit types + traverse and clone method bodies with tools like MethodBodyReader or CCI or Cecil. But what if method in source type was using some internal field or calling internal method, or maybe using property of outer class (in case of inner class)... As as result you will get invalid code. To correct it, your newly created type should be placed right near the original type. Luckily Cecil and CCI can do this trick.


 ? How to create a Dictionary with any types in Type variables?
 ? return generic IEnumerable when passing concrete type parameter for a generic method
 ? How do I check type of dynamic datatype at runtime?
 ? Casting to a generic list of variables of dynamic type
 ? Casting to a generic list of variables of dynamic type
 ? Casting to a generic list of variables of dynamic type
 ? Why does dynamic type work where casting does not?
 ? Generic method to type casting
 ? C# Numeric type casting between a generic and Built-in numeric type
 ? Cast dynamic to var