Loading a generic type by name when the generics arguments come from multiple assemblies

.net, assemblies, c#, reflection

Solution

You're going to have to do it the hard way I think. Fortunately it's not that hard. Pretty straightforward:

- Parse the type name into the type definition and the generic type arguments.

- Obtain the generic type definition object

- Obtain the type objects for each generic type argument

- Construct the generic type out of the generic type definition and the generic type arguments using the MakeGenericType method on the type definition object.

Problem

I need to create a type from its full name only Ex: "System.String" or "Tuple'2[string,Mytype]". there is no information about the assembly in the string. Here is what the code look like. ``` private static Type LoadType(string typeName) { // try loading the type Type type = Type.GetType(typeName, false); if (type != null) return type; // if the loading was not successfull iterate all the referenced assemblies and try to load the type. Assembly asm = Assembly.GetEntryAssembly(); AssemblyName[] referencedAssemblies = asm.GetReferencedAssemblies(); foreach (AssemblyName referencedAssemblyName in referencedAssemblies) { type = referencedAssembly.GetType(typeName, false); if (type != null) return type; } throw new TypeLoadException(string.Format("Could not load the Type '{0}'",typeName)); } ``` this method works when the type is not generic. But for generic types iterating through the assemblies always fails because no assemblies contains all the definitions required to build the type. Is there a way to provide multiples assemblies for type resolution when calling GetTypes ?

Original source

Related problems