Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type.GetType("namespace.a.b.ClassName") returns null

Tags:

c#

reflection

People also ask

Can GetType return null?

If typeName cannot be found, the call to the GetType(String) method returns null . It does not throw an exception.

What is return type of GetType ()?

The C# GetType() method is used to get type of current object. It returns the instance of Type class which is used for reflection.

What is use of GetType in C#?

GetType Method is used to find the type of the current instance. This method returns the instances of the Type class that are used for consideration.

How does type GetType work?

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.


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:

Type.GetType("namespace.qualified.TypeName, Assembly.Name")

You can also get the type without assembly qualified name but with the dll name also, for example:

Type myClassType = Type.GetType("TypeName,DllName");

I had the same situation and it worked for me. I needed an object of type "DataModel.QueueObject" and had a reference to "DataModel" so I got the type as follows:

Type type = Type.GetType("DataModel.QueueObject,DataModel");

The second string after the comma is the reference name (dll name).


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;
}

If the assembly is part of the build of an ASP.NET application, you can use the BuildManager class:

using System.Web.Compilation
...
BuildManager.GetType(typeName, false);

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;
}