Problem
This code:
Type.GetType("namespace.a.b.ClassName")
returns null.
I’ve got the following in the usings:
using namespace.a.b;
Update:
I need to get the type by string name because it exists but is in a separate class library.
Asked by Omu
Solution #1
Only when the type is found in either mscorlib.dll or the presently executing assembly does Type.GetType(“namespace.qualified.TypeName”) work.
You’ll need an assembly-qualified name if none of those things are true:
Type.GetType("namespace.qualified.TypeName, Assembly.Name")
Answered by DrPizza
Solution #2
You can also get the type without the assembly qualified name but with the dll name:
Type myClassType = Type.GetType("TypeName,DllName");
It worked for me when I was in the same scenario. I required a “DataModel.QueueObject” object and had a reference to “DataModel,” so I created one as follows:
Type type = Type.GetType("DataModel.QueueObject,DataModel");
The reference name is the second string following the comma (dll name).
Answered by Asaf Pala
Solution #3
Try this method.
public static Type GetType(string typeName)
{
var type = Type.GetType(typeName);
if (type != null) return type;
foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
{
type = a.GetType(typeName);
if (type != null)
return type;
}
return null;
}
Answered by peyman
Solution #4
You can use the BuildManager class if the assembly is part of an ASP.NET application’s build:
using System.Web.Compilation
...
BuildManager.GetType(typeName, false);
Answered by LarryBud
Solution #5
Dictionary<string, Type> typeCache;
...
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;
}
Answered by erikkallen
Post is based on https://stackoverflow.com/questions/1825147/type-gettypenamespace-a-b-classname-returns-null