How can I define multiple types with the same name and different type parameters using Reflection Emit?

.net, c#, generics, reflection.emit

Solution

You should avoid the conflict in the same way that C# and VB.Net do. When emiting a generic type name append a ` symbol and the number of generic parameters. For example the following type names actually get generated for the above

class Test`1 // Test<T>
class Test`2 // Test<T1,T2>

You can view this name mangling in the BCL with reflector. Set the language to IL instead of C# and it will show the actual names of type as emitted in metadata instead of the prettified language name.

Problem

How can I generate types like these using the System.Reflection.Emit libraries: ``` public class Test<T> {} public class Test<T1, T2> {} ``` When I call ModuleBuilder.DefineType(string) with the second type declaration, I get an exception because there is already another type in the module with the same name (I've already defined the type parameter on the first type). Any ideas?

Original source