Omu
Omu

Reputation: 71188

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

This code:

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

returns null.

I have in the usings:

using namespace.a.b;

The type exists, it's in a different class library, and I need to get it by it's name given as string.

Upvotes: 285

Views: 242436

Answers (18)

Geo Lew
Geo Lew

Reputation: 21

Here's what worked for me - I didn't want to build long library names, nor did I want to manually load libraries, so I programmatically found the library instead. Basically, I'm using the short name to find a match in GetTypes(), then I'm using that found construct to access the long name in the assembly. I really liked Marchino's LINQ implementation above, and wanted that to work for me, but I'm not good enough to work with two variables in LINQ statement :-)

    public static Type GetType(string type)
    {
        Type t = null;
        foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
        {
            foreach (var s in a.GetTypes())
            {
                if (s.Name == type)
                {
                    t = a.GetType(s.FullName); 
                    if (t != null) return t;
                }
            }
        }

        return t;
    }

Upvotes: 1

KWallace
KWallace

Reputation: 632

Very late reply, but if anyone is dealing with this a decade later:

There is a very, very small chance that your class in Visual Studio has a Build Action set to "Content" instead of "Compile".

Click on your class in Solution Explorer, then look at the properties.

Check that Build Action is "Compile", not "Content".

Upvotes: 0

peyman
peyman

Reputation: 991

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

Upvotes: 99

Florian Talour
Florian Talour

Reputation: 348

As Type.GetType(String) need the Type.AssemblyQualifiedName you should use Assembly.CreateQualifiedName(String, String).

string typeName = "MyNamespace.MyClass"; // Type.FullName
string assemblyName = "MyAssemblyName"; // MyAssembly.FullName or MyAssembly.GetName().Name
string assemblyQualifiedName = Assembly.CreateQualifiedName(assemblyName , typeName);
Type myClassType = Type.GetType(assemblyQualifiedName);

The Version, Culture and PublicKeyToken are not required for assemblyName that's why you can use MyAssembly.GetName().Name.

About Type.GetType(String) :

If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

Upvotes: 17

DrPizza
DrPizza

Reputation: 18340

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")

Upvotes: 354

Arash Masir
Arash Masir

Reputation: 205

For me, a "+" was the key! This is my class(it is a nested one) :

namespace PortalServices
{
public class PortalManagement : WebService
{
    public class Merchant
    {}
}
}

and this line of code worked:

Type type = Type.GetType("PortalServices.PortalManagement+Merchant");

Upvotes: 2

Marchino
Marchino

Reputation: 129

When I have only the class name I use this:

Type obj = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes()).Where(t => String.Equals(t.Name, _viewModelName, StringComparison.Ordinal)).First();

Upvotes: 11

jack_tux
jack_tux

Reputation: 429

Make sure that the comma is directly after the fully qualified name

typeof(namespace.a.b.ClassName, AssemblyName)

As this wont work

typeof(namespace.a.b.ClassName ,AssemblyName)

I was stumped for a few days on this one

Upvotes: 2

Numan KIZILIRMAK
Numan KIZILIRMAK

Reputation: 565

if your class is not in current assambly you must give qualifiedName and this code shows how to get qualifiedname of class

string qualifiedName = typeof(YourClass).AssemblyQualifiedName;

and then you can get type with qualifiedName

Type elementType = Type.GetType(qualifiedName);

Upvotes: 21

Darrel Lee
Darrel Lee

Reputation: 2460

I cheated. Since the types I want to create (by name) are all in In a dll I control, I just put a static method in the dll in the assembly that takes a simple name, and calls type.GetType from that context and returns the result.

The original purpose was so that the type could be specified by name in configuration data. I've since change the code so that the user specified a format to process. The format handler classes implement a interface that determines if the type can parse the specified format. I then use reflection to find types that implement the interface, and find one that handles the format. So now the configuration specifies a format name, a not a specific type. The reflection code can look at adjacent dlls and load, them so I have a sort poor man's plug-in architecture.

Upvotes: 0

Ozair Kafray
Ozair Kafray

Reputation: 13529

This solution above seems to be the best to me, but it didn't work for me, so I did it as follows:

AssemblyName assemblyName = AssemblyName.GetAssemblyName(HttpContext.Current.Server.MapPath("~\\Bin\\AnotherAssembly.dll"));
string typeAssemblyQualifiedName = string.Join(", ", "MyNamespace.MyType", assemblyName.FullName);

Type myType = Type.GetType(typeAssemblyQualifiedName);

The precondition is that you know the path of the assembly. In my case I know it because this is an assembly built from another internal project and its included in our project's bin folder.

In case it matters I am using Visual Studio 2013, my target .NET is 4.0. This is an ASP.NET project, so I am getting absolute path via HttpContext. However, absolute path is not a requirement as it seems from MSDN on AssemblyQualifiedNames

Upvotes: 0

Asaf Pala
Asaf Pala

Reputation: 2111

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).

Upvotes: 199

Stephan
Stephan

Reputation: 89

I am opening user controls depending on what user controls the user have access to specified in a database. So I used this method to get the TypeName...

Dim strType As String = GetType(Namespace.ClassName).AssemblyQualifiedName.ToString
Dim obj As UserControl = Activator.CreateInstance(Type.GetType(strType))

So now one can use the value returned in strType to create an instance of that object.

Upvotes: 5

LarryBud
LarryBud

Reputation: 1073

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

Upvotes: 31

erikkallen
erikkallen

Reputation: 34391

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

Upvotes: 27

Ismail Hawayel
Ismail Hawayel

Reputation: 2443

Try using the full type name that includes the assembly info, for example:

string typeName = @"MyCompany.MyApp.MyDomain.MyClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
Type myClassType = Type.GetType(typeName);

I had the same situation when I was using only the the namesspace.classname to get the type of a class in a different assembly and it would not work. Only worked when I included the assembly info in my type string as shown above.

Upvotes: 4

Ruben Bartelink
Ruben Bartelink

Reputation: 61795

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...)

Upvotes: 8

Guillaume
Guillaume

Reputation: 13128

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.

Upvotes: 4

Related Questions