Say I have this little bit of code:
public static void LoadSomething(Type t)
{            
    var t1 = Type.GetType(t.AssemblyQualifiedName);
    var t2 = t
        .Assembly
        .GetTypes()
        .First(ta => ta.AssemblyQualifiedName == t.AssemblyQualifiedName);
}
What happens is that t1 is null and t2 is not null. I was confused since if I call it like so...
LoadSomething(typeof(SomeObject));
then neither are null but what I am actually doing is more like this (not really, this is massively simplified but it illustrates my point):
LoadSomething(Assembly.LoadFile(@"C:\....dll").GetTypes().First());
So the first part of my question (for my information) is...
In the second case, since the assembly must be loaded up and I found the type out of it, why does Type.GetType return null?
And secondly (to actually solve my problem)...
Is there some other way that I could load a type when I only have the assembly qualified name as a string (that I know has been previously loaded by using the Assembly.Load methods)?
Is there some other way that I could load a type when I only have the assembly qualified name as a string (that I know has been previously loaded by using the Assembly.Load methods)?
Yes. There is a GetType overload that allows that. It takes an "assembly resolver" function as parameter:
public static Type LoadSomething(string assemblyQualifiedName)
{
    // This will return null
    // Just here to test that the simple GetType overload can't return the actual type
    var t0 = Type.GetType(assemblyQualifiedName);
    // Throws exception is type was not found
    return Type.GetType(
        assemblyQualifiedName,
        (name) =>
        {
            // Returns the assembly of the type by enumerating loaded assemblies
            // in the app domain            
            return AppDomain.CurrentDomain.GetAssemblies().Where(z => z.FullName == name.FullName).FirstOrDefault();
        },
        null,
        true);
}
private static void Main(string[] args)
{
    // Dynamically loads an assembly
    var assembly = Assembly.LoadFrom(@"C:\...\ClassLibrary1.dll");
    // Load the types using its assembly qualified name
    var loadedType = LoadSomething("ClassLibrary1.Class1, ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
    Console.ReadKey();
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With