Type.GetType return null

Tomas picture Tomas · Sep 2, 2011 · Viewed 25k times · Source

I am trying to use Type.GetType and pass "caLibClient.entity.Web2ImageEntity" full class name. The caLibClient.entity is namespace, located in separated assembly (caLibClient) and added to program reference assemblies list. The Type.GetType always return Null when I call it from program, what is wrong?

Answer

dlev picture dlev · Sep 2, 2011

You need to add the assembly name as well, since your type isn't in the executing assembly (nor mscorlib.) So the call should be:

var myType = Type.GetType("caLibClient.entity.Web2ImageEntity, FullAssemblyName");

From the Type.GetType() docs:

typeName
Type: System.String
The assembly-qualified name of the type to get. See AssemblyQualifiedName. 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.

From the docs for AssemblyQualifiedName, this is a sample name:

TopNamespace.SubNameSpace.ContainingClass+NestedClass, MyAssembly, Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089

Update: If you're already referencing the assembly in your project, and know at compile-time what the type-name is, you're better off saying

Type myType = typeof(caLibClient.entity.Web2ImageEntity);

since now you don't need to search for the type at run-time; the compiler will do everything for you.