tags:

views:

398

answers:

6

Type.GetType("namespace.a.b.ClassName") returns null
and I have in the usings:
using namespace.a.b;

UPDATE: the type exists, it's in a different class library, and i need to get it by string name

+10  A: 

Type.GetType("namespace.qualified.TypeName") only works when the type is found in either mscorlib.dll or the currently executing assembly.

If neither of those things are true, you'll need an assembly-qualified name.

DrPizza
the type exists, it's in a different class library, and i need to get it by string name
Omu
Then you will need to use an assembly qualified name.
DrPizza
@DrPizza, Pity you didn't privide any examples.
Shimmy
+1  A: 

Well, yeah, it returns null if the type doesn't exist. The using doesn't matter to Type.GetType().

So, it sems your type doesn't exist. Did you check if the assembly is loaded?

Maximilian Mayerl
the type exists, it's in a different class library, and i need to get it by string name
Omu
+1  A: 

If the assembly is referenced and the Class visible :

typeof(namespace.a.b.ClassName)

GetType returns null because the type is not found, with typeof, the compiler may help you to find out the error.

Guillaume
the type exists, it's in a different class library, and i need to get it by string name
Omu
+1  A: 

If it's a nested Type, you might be forgetting to transform a . to a +

Regardless, typeof( T).FullName will tell you what you should be saying

EDIT: BTW the usings (as I'm sure you know) are only directives to the compiler at compile time and cannot thus have any impact on the API call's success. (If you had project or assembly references, that could potentially have had influence - hence the information isnt useless, it just takes some filtering...)

Ruben Bartelink
+1  A: 

See this http://stackoverflow.com/questions/441680/how-can-i-retrieve-an-assemblys-qualified-type-name for info on how to get the assembly qualified name.

ShellShock
+1  A: 
public static bool TryFindType(string typeName, out Type t) {
    lock (typeCache) {
        if (!typeCache.TryGetValue(typeName, out t)) {
            foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) {
                t = a.GetType(typeName);
                if (t != null)
                    break;
            }
            typeCache[typeName] = t; // perhaps null
        }
    }
    return t != null;
}
erikkallen