I’m trying to locate a type at runtime from a list of assemblies; my code is something like this:
foreach (Assembly assembly in assembliesToSearch)
{
Type t = assembly.GetType(assemblyName);
if (t != null)
{
return t;
}
}
, and the problem that I have is that t is always coming up as null. Playing around with the debugger and the Intermediate window in VS2010, I noticed the following when I put a breakpoint inside the loop:
Type.GetType(typeof(MyNamespace.MyClass).AssemblyQualifiedName)
works OK, but
assembly.GetType(typeof(MyNamespace.MyClass).AssemblyQualifiedName)
does not (when assembly is the assembly that I know contains the class I’m looking for – in the debugger, I can put a watch on assembly.GetTypes(), browse to the class I’m trying to instantiate, and call assembly.GetType(“MyNamespace.MyClass, MyNamespace”)).
Does anyone know why searching all assemblies using Type.GetType() works, but searching the assembly that I know contains the type using assembly.GetType() does not?
From the MSDN docs for the two methods,
Type.GetType()expects an assembly-qualified name of a type whereasAssembly.GetType()expects the full name of the type. These are not the same thing.typeof(MyNamespace.MyClass).AssemblyQualifiedNameevaluates to an assembly-qualified name of a type (something likeMyNamespace.MyClass, MyAssembly, Version=1.0.0.0, Culture=neutral), so it does not work with theAssembly.GetType()call which is expecting a string in the formatMyNamespace.MyClass.This is probably down to the fact that when you pass the assembly-qualified name to the
Assembly.GetType()call, it is looking for a type in the assembly whose full name matches what you have supplied. It cannot find one, so you get anullreturned. This is not the case with theType.GetType()call as it expects to get an assembly-qualified name of a type and can locate both the assembly and the type.Something to note:
If you are “trying to locate a type at runtime from a list of assemblies” as you say, you are probably better off using the
Assembly.GetType()call on each assembly in the list and passing in the type’s full name.Type.GetType()will most likely be using the references of the currently assembly to resolve the type, so if the type exists in an assembly that is not a reference, it will not be found.