views:

1455

answers:

2

GetType() returns null when the type exists in an unreferenced assembly. For example, when the following is called "localType" is always null (even when using the full namespace name of the class):

Type localType = Type.GetType("NamespaceX.ProjectX.ClassX");

I don't see any reason why Type.GetType shouldn't be able to retrieve a type from an unreferenced assembly, so

How can the type of an unreferenced assembly be retrieved?

+1  A: 

From the MSDN documentation

If the requested type is non-public and the caller does not have ReflectionPermission to reflect non-public objects outside the current assembly, this method returns null.

It also indicates null will be returned if the assembly isn't loaded from disk.

One work around you might try is loading the assembly and then using the GetType methods on the assembly directly. Admittedly from the documentation it sounds like it should have thrown an exception if the problem was in loading the assembly.

Jeremy Wilde
+3  A: 

Use LoadFrom to load the unreferenced assembly from it's location. And then call GetType.

Assembly assembly = Assembly.LoadFrom("c:\ProjectX\bin\release\ProjectX.dll");
Type type = assembly.GetType("NamespaceX.ProjectX.ClassX");

If the assembly to load is in the private path of the assembly you're loading from (like "c:\ProjectY\bin\release\ProjectX.dll"), you can use Load.

Assembly assembly = Assembly.Load("ProjectX.dll");
Type type = assembly.GetType("NamespaceX.ProjectX.ClassX");
Anthony Mastrean
I think `Load` follows the rules here... http://stackoverflow.com/questions/49972
Anthony Mastrean