Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would Type.GetType() work and Assembly.GetType() not work?

Tags:

c#

reflection

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?

like image 207
David Keaveny Avatar asked Sep 11 '11 23:09

David Keaveny


1 Answers

From the MSDN docs for the two methods, Type.GetType() expects an assembly-qualified name of a type whereas Assembly.GetType() expects the full name of the type. These are not the same thing.

typeof(MyNamespace.MyClass).AssemblyQualifiedName evaluates to an assembly-qualified name of a type (something like MyNamespace.MyClass, MyAssembly, Version=1.0.0.0, Culture=neutral), so it does not work with the Assembly.GetType() call which is expecting a string in the format MyNamespace.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 a null returned. This is not the case with the Type.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.

like image 178
adrianbanks Avatar answered Sep 28 '22 02:09

adrianbanks