Type.GetType Method

Definition

Gets a Type object that represents the specified type.

Overloads

GetType()

Gets the current Type.

GetType(String)

Gets the Type with the specified name, performing a case-sensitive search.

GetType(String, Boolean)

Gets the Type with the specified name, performing a case-sensitive search and specifying whether to throw an exception if the type is not found.

GetType(String, Boolean, Boolean)

Gets the Type with the specified name, specifying whether to throw an exception if the type is not found and whether to perform a case-sensitive search.

GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>)

Gets the type with the specified name, optionally providing custom methods to resolve the assembly and the type.

GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean)

Gets the type with the specified name, specifying whether to throw an exception if the type is not found, and optionally providing custom methods to resolve the assembly and the type.

GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean)

Gets the type with the specified name, specifying whether to perform a case-sensitive search and whether to throw an exception if the type is not found, and optionally providing custom methods to resolve the assembly and the type.

GetType()

Gets the current Type.

public:
 Type ^ GetType();
public:
 virtual Type ^ GetType();
public Type GetType ();
override this.GetType : unit -> Type
Public Function GetType () As Type

Returns

Type

The current Type.

Implements

Exceptions

A class initializer is invoked and throws an exception.

See also

Applies to

GetType(String)

Gets the Type with the specified name, performing a case-sensitive search.

public:
 static Type ^ GetType(System::String ^ typeName);
public static Type GetType (string typeName);
public static Type? GetType (string typeName);
static member GetType : string -> Type
Public Shared Function GetType (typeName As String) As Type

Parameters

typeName
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/System.Private.CoreLib.dll, it is sufficient to supply the type name qualified by its namespace.

Returns

Type

The type with the specified name, if found; otherwise, null.

Exceptions

typeName is null.

A class initializer is invoked and throws an exception.

typeName represents a generic type that has a pointer type, a ByRef type, or Void as one of its type arguments.

-or-

typeName represents a generic type that has an incorrect number of type arguments.

-or-

typeName represents a generic type, and one of its type arguments does not satisfy the constraints for the corresponding type parameter.

typeName represents an array of TypedReference.

The assembly or one of its dependencies was found, but could not be loaded.

Note: In .NET for Windows Store apps or the Portable Class Library, catch the base class exception, IOException, instead.

The assembly or one of its dependencies is not valid.

-or-

Version 2.0 or later of the common language runtime is currently loaded, and the assembly was compiled with a later version.

Examples

The following example retrieves the type of System.Int32 and uses that type object to display the FullName property of System.Int32.

using namespace System;

int main()
{
   try {
      // Get the type of a specified class.
      Type^ myType1 = Type::GetType( "System.Int32" );
      Console::WriteLine( "The full name is {0}.\n", myType1->FullName );
   }
   catch ( TypeLoadException^ e ) {
       Console::WriteLine("{0}: Unable to load type System.Int32",
                          e->GetType()->Name);
   }

   try {
      // Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
      Type^ myType2 = Type::GetType( "NoneSuch", true );
      Console::WriteLine( "The full name is {0}.", myType2->FullName );
   }
   catch ( TypeLoadException^ e ) {
       Console::WriteLine("{0}: Unable to load type NoneSuch",
                          e->GetType()->Name);
   }

}
// The example displays the following output:
//       The full name is System.Int32.
//
//       TypeLoadException: Unable to load type NoneSuch
using System;

class Example
{
     public static void Main()
     {
         try {
             // Get the type of a specified class.
             Type myType1 = Type.GetType("System.Int32");
             Console.WriteLine("The full name is {0}.\n", myType1.FullName);
         }
         catch (TypeLoadException e)
         {
            Console.WriteLine("{0}: Unable to load type System.Int32", e.GetType().Name);
         }

         try {
             // Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
             Type myType2 = Type.GetType("NoneSuch", true);
             Console.WriteLine("The full name is {0}.", myType2.FullName);
         }
         catch(TypeLoadException e) {
            Console.WriteLine("{0}: Unable to load type NoneSuch", e.GetType().Name);
         }
     }
}
// The example displays the following output:
//       The full name is System.Int32.
//
//       TypeLoadException: Unable to load type NoneSuch
open System

try
    // Get the type of a specified class.
    let myType1 = Type.GetType "System.Int32"
    printfn $"The full name is {myType1.FullName}.\n"
with :? TypeLoadException as e ->
    printfn $"{e.GetType().Name}: Unable to load type System.Int32"

try
    // Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
    let myType2 = Type.GetType("NoneSuch", true)
    printfn $"The full name is {myType2.FullName}."
with :? TypeLoadException as e ->
    printfn $"{e.GetType().Name}: Unable to load type NoneSuch"
// The example displays the following output:
//       The full name is System.Int32.
//
//       TypeLoadException: Unable to load type NoneSuch
Class Example
     Public Shared Sub Main()
         Try
             ' Get the type of the specified class.
             Dim myType1 As Type = Type.GetType("System.Int32")
             Console.WriteLine("The full name is {0}.", myType1.FullName)
         Catch e As TypeLoadException
             Console.WriteLine("{0}: Unable to load type System.Int32",
                               e.GetType().Name)
         End Try

         Console.WriteLine()

         Try
             ' Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
             Dim myType2 As Type = Type.GetType("NoneSuch", True)
             Console.WriteLine("The full name is {0}.", myType2.FullName)
         Catch e As TypeLoadException
             Console.WriteLine("{0}: Unable to load type NoneSuch", e.GetType().Name)
         End Try
     End Sub
End Class
' The example displays the following output:
'       The full name is System.Int32.
'
'       TypeLoadException: Unable to load type NoneSuch

Remarks

You can use the GetType method to obtain a Type object for a type in another assembly if you know its assembly-qualified name, which can be obtained from AssemblyQualifiedName. GetType causes loading of the assembly specified in typeName. You can also load an assembly using the Assembly.Load method, and then use the Assembly.GetType or Assembly.GetTypes method to get Type objects. If a type is in an assembly known to your program at compile time, it is more efficient to use typeof in C# or the GetType operator in Visual Basic.

Note

If typeName cannot be found, the call to the GetType(String) method returns null. It does not throw an exception. To control whether an exception is thrown, call an overload of the GetType method that has a throwOnError parameter.

GetType only works on assemblies loaded from disk. If you call GetType to look up a type defined in a dynamic assembly defined using the System.Reflection.Emit services, you might get inconsistent behavior. The behavior depends on whether the dynamic assembly is persistent, that is, created using the RunAndSave or Save access modes of the System.Reflection.Emit.AssemblyBuilderAccess enumeration. If the dynamic assembly is persistent and has been written to disk before GetType is called, the loader finds the saved assembly on disk, loads that assembly, and retrieves the type from that assembly. If the assembly has not been saved to disk when GetType is called, the method returns null. GetType does not understand transient dynamic assemblies; therefore, calling GetType to retrieve a type in a transient dynamic assembly returns null.

To use GetType on a dynamic module, subscribe to the AppDomain.AssemblyResolve event and call GetType before saving. Otherwise, you will get two copies of the assembly in memory.

The following table shows what members of a base class are returned by the Get methods when reflecting on a type.

Member Type Static Non-Static
Constructor No No
Field No Yes. A field is always hide-by-name-and-signature.
Event Not applicable The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below.
Method No Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature.
Nested Type No No
Property Not applicable The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.

  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.

  3. Custom attributes are not part of the common type system.

Arrays or COM types are not searched for unless they have already been loaded into the table of available classes.

typeName can be the type name qualified by its namespace or an assembly-qualified name that includes an assembly name specification. See AssemblyQualifiedName.

If typeName includes the namespace but not the assembly name, this method searches only the calling object's assembly and mscorlib.dll/System.Private.CoreLib.dll, in that order. If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly. If the assembly has a strong name, a complete assembly name is required.

The AssemblyQualifiedName property returns a fully qualified type name including nested types, the assembly name, and generic type arguments. All compilers that support the common language runtime will emit the simple name of a nested class, and reflection constructs a mangled name when queried, in accordance with the following conventions.

Note

In the .NET Framework version 2.0, processor architecture is added to assembly identity, and can be specified as part of assembly name strings. For example, "ProcessorArchitecture=msil". However, it is not included in the string returned by the AssemblyQualifiedName property, for compatibility reasons. You can also load types by creating an AssemblyName object and passing it to an appropriate overload of the Load method. You can then use the Assembly.GetType method to load types from the assembly. See also AssemblyName.ProcessorArchitecture.

Delimiter Meaning
Backslash (\) Escape character.
Backtick (`) Precedes one or more digits representing the number of type parameters, located at the end of the name of a generic type.
Brackets ([]) Enclose a generic type argument list, for a constructed generic type; within a type argument list, enclose an assembly-qualified type.
Comma (,) Precedes the Assembly name.
Period (.) Denotes namespace identifiers.
Plus sign (+) Precedes a nested class.

For example, the fully qualified name for a class might look like this:

TopNamespace.SubNameSpace.ContainingClass+NestedClass,MyAssembly  

If the namespace were TopNamespace.Sub+Namespace, then the string would have to precede the plus sign (+) with an escape character (\) to prevent it from being interpreted as a nesting separator. Reflection emits this string as follows:

TopNamespace.Sub\+Namespace.ContainingClass+NestedClass,MyAssembly  

A "++" becomes "\+\+", and a "\" becomes "\\".

This qualified name can be persisted and later used to load the Type. To search for and load a Type, use GetType either with the type name only or with the assembly qualified type name. GetType with the type name only will look for the Type in the caller's assembly and then in the System assembly. GetType with the assembly qualified type name will look for the Type in any assembly.

Type names may include trailing characters that denote additional information about the type, such as whether the type is a reference type, a pointer type or an array type. To retrieve the type name without these trailing characters, use t.GetElementType().ToString(), where t is the type.

Spaces are relevant in all type name components except the assembly name. In the assembly name, spaces before the ',' separator are relevant, but spaces after the ',' separator are ignored.

The name of a generic type ends with a backtick (`) followed by digits representing the number of generic type arguments. The purpose of this name mangling is to allow compilers to support generic types with the same name but with different numbers of type parameters, occurring in the same scope. For example, reflection returns the mangled names Tuple`1 and Tuple`2 from the generic methods Tuple(Of T) and Tuple(Of T0, T1) in Visual Basic, or Tuple<T> and Tuple<T0, T1> in Visual C#.

For generic types, the type argument list is enclosed in brackets, and the type arguments are separated by commas. For example, a generic Dictionary<TKey,TValue> has two type parameters. A Dictionary<TKey,TValue> of MyType with keys of type String might be represented as follows:

System.Collections.Generic.Dictionary`2[System.String,MyType]  

To specify an assembly-qualified type within a type argument list, enclose the assembly-qualified type within brackets. Otherwise, the commas that separate the parts of the assembly-qualified name are interpreted as delimiting additional type arguments. For example, a Dictionary<TKey,TValue> of MyType fromMyAssembly.dll, with keys of type String, might be specified as follows:

Type.GetType("System.Collections.Generic.Dictionary`2[System.String,[MyType,MyAssembly]]")  

Note

An assembly-qualified type can be enclosed in brackets only when it appears within a type parameter list. The rules for searching assemblies for qualified and unqualified types in type parameter lists are the same as the rules for qualified and unqualified nongeneric types.

Nullable types are a special case of generic types. For example, a nullable Int32 is represented by the string "System.Nullable`1[System.Int32]".

Note

In C#, C++, and Visual Basic you can also get nullable types using type operators. For example, the nullable Boolean type is returned by typeof(Nullable<bool>) in C#, by Nullable<Boolean>::typeid in C++, and by GetType(Nullable(Of Boolean)) in Visual Basic.

The following table shows the syntax you use with GetType for various types.

To Get Use
A nullable Int32 Type.GetType("System.Nullable`1[System.Int32]")
An unmanaged pointer to MyType Type.GetType("MyType*")
An unmanaged pointer to a pointer to MyType Type.GetType("MyType**")
A managed pointer or reference to MyType Type.GetType("MyType&"). Note that unlike pointers, references are limited to one level.
A parent class and a nested class Type.GetType("MyParentClass+MyNestedClass")
A one-dimensional array with a lower bound of 0 Type.GetType("MyType[]")
A one-dimensional array with an unknown lower bound Type.GetType("MyType[*]")
An n-dimensional array A comma (,) inside the brackets a total of n-1 times. For example, System.Object[,,] represents a three-dimensional Object array.
An array of one-dimensional arrays Type.GetType("MyType[][]")
A rectangular two-dimensional array with unknown lower bounds Type.GetType("MyType[,]")
A generic type with one type argument Type.GetType("MyGenericType`1[MyType]")
A generic type with two type arguments Type.GetType("MyGenericType`2[MyType,AnotherType]")
A generic type with two assembly-qualified type arguments Type.GetType("MyGenericType`2[[MyType,MyAssembly],[AnotherType,AnotherAssembly]]")
An assembly-qualified generic type with an assembly-qualified type argument Type.GetType("MyGenericType`1[[MyType,MyAssembly]],MyGenericTypeAssembly")
A generic type whose type argument is a generic type with two type arguments Type.GetType("MyGenericType`1[AnotherGenericType`2[MyType,AnotherType]]")

See also

Applies to

GetType(String, Boolean)

Gets the Type with the specified name, performing a case-sensitive search and specifying whether to throw an exception if the type is not found.

public:
 static Type ^ GetType(System::String ^ typeName, bool throwOnError);
public static Type GetType (string typeName, bool throwOnError);
public static Type? GetType (string typeName, bool throwOnError);
static member GetType : string * bool -> Type
Public Shared Function GetType (typeName As String, throwOnError As Boolean) As Type

Parameters

typeName
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/System.Private.CoreLib.dll, it is sufficient to supply the type name qualified by its namespace.

throwOnError
Boolean

true to throw an exception if the type cannot be found; false to return null. Specifying false also suppresses some other exception conditions, but not all of them. See the Exceptions section.

Returns

Type

The type with the specified name. If the type is not found, the throwOnError parameter specifies whether null is returned or an exception is thrown. In some cases, an exception is thrown regardless of the value of throwOnError. See the Exceptions section.

Exceptions

typeName is null.

A class initializer is invoked and throws an exception.

throwOnError is true and the type is not found.

-or-

throwOnError is true and typeName contains invalid characters, such as an embedded tab.

-or-

throwOnError is true and typeName is an empty string.

-or-

throwOnError is true and typeName represents an array type with an invalid size.

-or-

typeName represents an array of TypedReference.

throwOnError is true and typeName contains invalid syntax. For example, "MyType[,*,]".

-or-

typeName represents a generic type that has a pointer type, a ByRef type, or Void as one of its type arguments.

-or-

typeName represents a generic type that has an incorrect number of type arguments.

-or-

typeName represents a generic type, and one of its type arguments does not satisfy the constraints for the corresponding type parameter.

throwOnError is true and the assembly or one of its dependencies was not found.

The assembly or one of its dependencies was found, but could not be loaded.

Note: In .NET for Windows Store apps or the Portable Class Library, catch the base class exception, IOException, instead.

The assembly or one of its dependencies is not valid.

-or-

Version 2.0 or later of the common language runtime is currently loaded, and the assembly was compiled with a later version.

Examples

The following example retrieves the type of System.Int32 and uses that type object to display the FullName property of System.Int32. If a type object refers to an assembly that does not exist, this example throws an exception.

using namespace System;

int main()
{
   try {
      // Get the type of a specified class.
      Type^ myType1 = Type::GetType( "System.Int32" );
      Console::WriteLine( "The full name is {0}.\n", myType1->FullName );
   }
   catch ( TypeLoadException^ e ) {
       Console::WriteLine("{0}: Unable to load type System.Int32",
                          e->GetType()->Name);
   }

   try {
      // Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
      Type^ myType2 = Type::GetType( "NoneSuch", true );
      Console::WriteLine( "The full name is {0}.", myType2->FullName );
   }
   catch ( TypeLoadException^ e ) {
       Console::WriteLine("{0}: Unable to load type NoneSuch",
                          e->GetType()->Name);
   }

}
// The example displays the following output:
//       The full name is System.Int32.
//
//       TypeLoadException: Unable to load type NoneSuch
using System;

class Example
{
     public static void Main()
     {
         try {
             // Get the type of a specified class.
             Type myType1 = Type.GetType("System.Int32");
             Console.WriteLine("The full name is {0}.\n", myType1.FullName);
         }
         catch (TypeLoadException e)
         {
            Console.WriteLine("{0}: Unable to load type System.Int32", e.GetType().Name);
         }

         try {
             // Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
             Type myType2 = Type.GetType("NoneSuch", true);
             Console.WriteLine("The full name is {0}.", myType2.FullName);
         }
         catch(TypeLoadException e) {
            Console.WriteLine("{0}: Unable to load type NoneSuch", e.GetType().Name);
         }
     }
}
// The example displays the following output:
//       The full name is System.Int32.
//
//       TypeLoadException: Unable to load type NoneSuch
open System

try
    // Get the type of a specified class.
    let myType1 = Type.GetType "System.Int32"
    printfn $"The full name is {myType1.FullName}.\n"
with :? TypeLoadException as e ->
    printfn $"{e.GetType().Name}: Unable to load type System.Int32"

try
    // Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
    let myType2 = Type.GetType("NoneSuch", true)
    printfn $"The full name is {myType2.FullName}."
with :? TypeLoadException as e ->
    printfn $"{e.GetType().Name}: Unable to load type NoneSuch"
// The example displays the following output:
//       The full name is System.Int32.
//
//       TypeLoadException: Unable to load type NoneSuch
Class Example
     Public Shared Sub Main()
         Try
             ' Get the type of the specified class.
             Dim myType1 As Type = Type.GetType("System.Int32")
             Console.WriteLine("The full name is {0}.", myType1.FullName)
         Catch e As TypeLoadException
             Console.WriteLine("{0}: Unable to load type System.Int32",
                               e.GetType().Name)
         End Try

         Console.WriteLine()

         Try
             ' Since NoneSuch does not exist in this assembly, GetType throws a TypeLoadException.
             Dim myType2 As Type = Type.GetType("NoneSuch", True)
             Console.WriteLine("The full name is {0}.", myType2.FullName)
         Catch e As TypeLoadException
             Console.WriteLine("{0}: Unable to load type NoneSuch", e.GetType().Name)
         End Try
     End Sub
End Class
' The example displays the following output:
'       The full name is System.Int32.
'
'       TypeLoadException: Unable to load type NoneSuch

Remarks

You can use the GetType method to obtain a Type object for a type in another assembly if you know its assembly-qualified name, which can be obtained from AssemblyQualifiedName. GetType causes loading of the assembly specified in typeName. You can also load an assembly using the Assembly.Load method, and then use the Assembly.GetType or Assembly.GetTypes method to get Type objects. If a type is in an assembly known to your program at compile time, it is more efficient to use typeof in C# or the GetType operator in Visual Basic.

GetType only works on assemblies loaded from disk. If you call GetType to look up a type defined in a dynamic assembly defined using the System.Reflection.Emit services, you might get inconsistent behavior. The behavior depends on whether the dynamic assembly is persistent, that is, created using the RunAndSave or Save access modes of the System.Reflection.Emit.AssemblyBuilderAccess enumeration. If the dynamic assembly is persistent and has been written to disk before GetType is called, the loader finds the saved assembly on disk, loads that assembly, and retrieves the type from that assembly. If the assembly has not been saved to disk when GetType is called, the method returns null. GetType does not understand transient dynamic assemblies; therefore, calling GetType to retrieve a type in a transient dynamic assembly returns null.

To use GetType on a dynamic module, subscribe to the AppDomain.AssemblyResolve event and call GetType before saving. Otherwise, you will get two copies of the assembly in memory.

The throwOnError parameter specifies what happens when the type is not found, and also suppresses certain other exception conditions, as described in the Exceptions section. Some exceptions are thrown regardless of the value of throwOnError. For example, if the type is found but cannot be loaded, a TypeLoadException is thrown even if throwOnError is false.

The following table shows what members of a base class are returned by the Get methods when reflecting on a type.

Member Type Static Non-Static
Constructor No No
Field No Yes. A field is always hide-by-name-and-signature.
Event Not applicable The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below.
Method No Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature.
Nested Type No No
Property Not applicable The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.

  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.

  3. Custom attributes are not part of the common type system.

Arrays or COM types are not searched for unless they have already been loaded into the table of available classes.

typeName can be the type name qualified by its namespace or an assembly-qualified name that includes an assembly name specification. See AssemblyQualifiedName.

If typeName includes the namespace but not the assembly name, this method searches only the calling object's assembly and mscorlib.dll/System.Private.CoreLib.dll, in that order. If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly. If the assembly has a strong name, a complete assembly name is required.

The AssemblyQualifiedName property returns a fully qualified type name including nested types, the assembly name, and generic arguments. All compilers that support the common language runtime will emit the simple name of a nested class, and reflection constructs a mangled name when queried, in accordance with the following conventions.

Note

In the .NET Framework version 2.0, processor architecture is added to assembly identity, and can be specified as part of assembly name strings. For example, "ProcessorArchitecture=msil". However, it is not included in the string returned by the AssemblyQualifiedName property, for compatibility reasons. You can also load types by creating an AssemblyName object and passing it to an appropriate overload of the Load method. You can then use the Assembly.GetType method to load types from the assembly. See also AssemblyName.ProcessorArchitecture.

Delimiter Meaning
Backslash (\) Escape character.
Backtick (`) Precedes one or more digits representing the number of type parameters, located at the end of the name of a generic type.
Brackets ([]) Enclose a generic type argument list, for a constructed generic type; within a type argument list, enclose an assembly-qualified type.
Comma (,) Precedes the Assembly name.
Period (.) Denotes namespace identifiers.
Plus sign (+) Precedes a nested class.

For example, the fully qualified name for a class might look like this:

TopNamespace.SubNameSpace.ContainingClass+NestedClass,MyAssembly  

If the namespace were TopNamespace.Sub+Namespace, then the string would have to precede the plus sign (+) with an escape character (\) to prevent it from being interpreted as a nesting separator. Reflection emits this string as follows:

TopNamespace.Sub\+Namespace.ContainingClass+NestedClass,MyAssembly  

A "++" becomes "\+\+", and a "\" becomes "\\".

This qualified name can be persisted and later used to load the Type. To search for and load a Type, use GetType either with the type name only or with the assembly qualified type name. GetType with the type name only will look for the Type in the caller's assembly and then in the System assembly. GetType with the assembly qualified type name will look for the Type in any assembly.

Type names may include trailing characters that denote additional information about the type, such as whether the type is a reference type, a pointer type or an array type. To retrieve the type name without these trailing characters, use t.GetElementType().ToString(), where t is the type.

Spaces are relevant in all type name components except the assembly name. In the assembly name, spaces before the ',' separator are relevant, but spaces after the ',' separator are ignored.

The name of a generic type ends with a backtick (`) followed by digits representing the number of generic type arguments. The purpose of this name mangling is to allow compilers to support generic types with the same name but with different numbers of type parameters, occurring in the same scope. For example, reflection returns the mangled names Tuple`1 and Tuple`2 from the generic methods Tuple(Of T) and Tuple(Of T0, T1) in Visual Basic, or Tuple<T> and Tuple<T0, T1> in Visual C#.

For generic types, the type argument list is enclosed in brackets, and the type arguments are separated by commas. For example, a generic Dictionary<TKey,TValue> has two type parameters. A Dictionary<TKey,TValue> of MyType with keys of type String might be represented as follows:

System.Collections.Generic.Dictionary`2[System.String,MyType]  

To specify an assembly-qualified type within a type argument list, enclose the assembly-qualified type within brackets. Otherwise, the commas that separate the parts of the assembly-qualified name are interpreted as delimiting additional type arguments. For example, a Dictionary<TKey,TValue> of MyType from MyAssembly.dll, with keys of type String, might be specified as follows:

Type.GetType("System.Collections.Generic.Dictionary`2[System.String,[MyType,MyAssembly]]")  

Note

An assembly-qualified type can be enclosed in brackets only when it appears within a type parameter list. The rules for searching assemblies for qualified and unqualified types in type parameter lists are the same as the rules for qualified and unqualified nongeneric types.

Nullable types are a special case of generic types. For example, a nullable Int32 is represented by the string "System.Nullable`1[System.Int32]".

Note

In C#, C++, and Visual Basic you can also get nullable types using type operators. For example, the nullable Boolean type is returned by typeof(Nullable<bool>) in C#, by Nullable<Boolean>::typeid in C++, and by GetType(Nullable(Of Boolean)) in Visual Basic.

The following table shows the syntax you use with GetType for various types.

To Get Use
A nullable Int32 Type.GetType("System.Nullable`1[System.Int32]")
An unmanaged pointer to MyType Type.GetType("MyType*")
An unmanaged pointer to a pointer to MyType Type.GetType("MyType**")
A managed pointer or reference to MyType Type.GetType("MyType&"). Note that unlike pointers, references are limited to one level.
A parent class and a nested class Type.GetType("MyParentClass+MyNestedClass")
A one-dimensional array with a lower bound of 0 Type.GetType("MyArray[]")
A one-dimensional array with an unknown lower bound Type.GetType("MyArray[*]")
An n-dimensional array A comma (,) inside the brackets a total of n-1 times. For example, System.Object[,,] represents a three-dimensional Object array.
A two-dimensional array's array Type.GetType("MyArray[][]")
A rectangular two-dimensional array with unknown lower bounds Type.GetType("MyArray[,]")
A generic type with one type argument Type.GetType("MyGenericType`1[MyType]")
A generic type with two type arguments Type.GetType("MyGenericType`2[MyType,AnotherType]")
A generic type with two assembly-qualified type arguments Type.GetType("MyGenericType`2[[MyType,MyAssembly],[AnotherType,AnotherAssembly]]")
An assembly-qualified generic type with an assembly-qualified type argument Type.GetType("MyGenericType`1[[MyType,MyAssembly]],MyGenericTypeAssembly")
A generic type whose type argument is a generic type with two type arguments Type.GetType("MyGenericType`1[AnotherGenericType`2[MyType,AnotherType]]")

See also

Applies to

GetType(String, Boolean, Boolean)

Gets the Type with the specified name, specifying whether to throw an exception if the type is not found and whether to perform a case-sensitive search.

public:
 static Type ^ GetType(System::String ^ typeName, bool throwOnError, bool ignoreCase);
public static Type GetType (string typeName, bool throwOnError, bool ignoreCase);
public static Type? GetType (string typeName, bool throwOnError, bool ignoreCase);
static member GetType : string * bool * bool -> Type
Public Shared Function GetType (typeName As String, throwOnError As Boolean, ignoreCase As Boolean) As Type

Parameters

typeName
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/System.Private.CoreLib.dll, it is sufficient to supply the type name qualified by its namespace.

throwOnError
Boolean

true to throw an exception if the type cannot be found; false to return null. Specifying false also suppresses some other exception conditions, but not all of them. See the Exceptions section.

ignoreCase
Boolean

true to perform a case-insensitive search for typeName, false to perform a case-sensitive search for typeName.

Returns

Type

The type with the specified name. If the type is not found, the throwOnError parameter specifies whether null is returned or an exception is thrown. In some cases, an exception is thrown regardless of the value of throwOnError. See the Exceptions section.

Exceptions

typeName is null.

A class initializer is invoked and throws an exception.

throwOnError is true and the type is not found.

-or-

throwOnError is true and typeName contains invalid characters, such as an embedded tab.

-or-

throwOnError is true and typeName is an empty string.

-or-

throwOnError is true and typeName represents an array type with an invalid size.

-or-

typeName represents an array of TypedReference.

throwOnError is true and typeName contains invalid syntax. For example, "MyType[,*,]".

-or-

typeName represents a generic type that has a pointer type, a ByRef type, or Void as one of its type arguments.

-or-

typeName represents a generic type that has an incorrect number of type arguments.

-or-

typeName represents a generic type, and one of its type arguments does not satisfy the constraints for the corresponding type parameter.

throwOnError is true and the assembly or one of its dependencies was not found.

The assembly or one of its dependencies was found, but could not be loaded.

The assembly or one of its dependencies is not valid.

-or-

Version 2.0 or later of the common language runtime is currently loaded, and the assembly was compiled with a later version.

Remarks

You can use the GetType method to obtain a Type object for a type in another assembly if you know its assembly-qualified name, which can be obtained from AssemblyQualifiedName. GetType causes loading of the assembly specified in typeName. You can also load an assembly using the Assembly.Load method, and then use the Assembly.GetType or Assembly.GetTypes method to get Type objects. If a type is in an assembly known to your program at compile time, it is more efficient to use typeof in C# or the GetType operator in Visual Basic.

GetType only works on assemblies loaded from disk. If you call GetType to look up a type defined in a dynamic assembly defined using the System.Reflection.Emit services, you might get inconsistent behavior. The behavior depends on whether the dynamic assembly is persistent, that is, created using the RunAndSave or Save access modes of the System.Reflection.Emit.AssemblyBuilderAccess enumeration. If the dynamic assembly is persistent and has been written to disk before GetType is called, the loader finds the saved assembly on disk, loads that assembly, and retrieves the type from that assembly. If the assembly has not been saved to disk when GetType is called, the method returns null. GetType does not understand transient dynamic assemblies; therefore, calling GetType to retrieve a type in a transient dynamic assembly returns null.

To use GetType on a dynamic module, subscribe to the AppDomain.AssemblyResolve event and call GetType before saving. Otherwise, you will get two copies of the assembly in memory.

The throwOnError parameter specifies what happens when the type is not found, and also suppresses certain other exception conditions, as described in the Exceptions section. Some exceptions are thrown regardless of the value of throwOnError. For example, if the type is found but cannot be loaded, a TypeLoadException is thrown even if throwOnError is false.

The following table shows what members of a base class are returned by the Get methods when reflecting on a type.

Member Type Static Non-Static
Constructor No No
Field No Yes. A field is always hide-by-name-and-signature.
Event Not applicable The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below.
Method No Yes. A method (both virtual and non-virtual) can be hide-by-name or hide-by-name-and-signature.
Nested Type No No
Property Not applicable The common type system rule is that the inheritance is the same as that of the methods that implement the property. Reflection treats properties as hide-by-name-and-signature. See note 2 below.
  1. Hide-by-name-and-signature considers all of the parts of the signature, including custom modifiers, return types, parameter types, sentinels, and unmanaged calling conventions. This is a binary comparison.

  2. For reflection, properties and events are hide-by-name-and-signature. If you have a property with both a get and a set accessor in the base class, but the derived class has only a get accessor, the derived class property hides the base class property, and you will not be able to access the setter on the base class.

  3. Custom attributes are not part of the common type system.

Arrays or COM types are not searched for unless they have already been loaded into the table of available classes.

typeName can be the type name qualified by its namespace or an assembly-qualified name that includes an assembly name specification. See AssemblyQualifiedName.

If typeName includes the namespace but not the assembly name, this method searches only the calling object's assembly and mscorlib.dll/System.Private.CoreLib.dll, in that order. If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly. If the assembly has a strong name, a complete assembly name is required.

The AssemblyQualifiedName property returns a fully qualified type name including nested types, the assembly name, and type arguments. All compilers that support the common language runtime will emit the simple name of a nested class, and reflection constructs a mangled name when queried, in accordance with the following conventions.

Note

In the .NET Framework version 2.0, processor architecture is added to assembly identity, and can be specified as part of assembly name strings. For example, "ProcessorArchitecture=msil". However, it is not included in the string returned by the AssemblyQualifiedName property, for compatibility reasons. You can also load types by creating an AssemblyName object and passing it to an appropriate overload of the Load method. You can then use the Assembly.GetType method to load types from the assembly. See also AssemblyName.ProcessorArchitecture.

Delimiter Meaning
Backslash (\) Escape character.
Backtick (`) Precedes one or more digits representing the number of type parameters, located at the end of the name of a generic type.
Brackets ([]) Enclose a generic type argument list, for a constructed generic type; within a type argument list, enclose an assembly-qualified type.
Comma (,) Precedes the Assembly name.
Period (.) Denotes namespace identifiers.
Plus sign (+) Precedes a nested class.

For example, the fully qualified name for a class might look like this:

TopNamespace.SubNameSpace.ContainingClass+NestedClass,MyAssembly  

If the namespace were TopNamespace.Sub+Namespace, then the string would have to precede the plus sign (+) with an escape character (\) to prevent it from being interpreted as a nesting separator. Reflection emits this string as follows:

TopNamespace.Sub\+Namespace.ContainingClass+NestedClass,MyAssembly  

A "++" becomes "\+\+", and a "\" becomes "\\".

This qualified name can be persisted and later used to load the Type. To search for and load a Type, use GetType either with the type name only or with the assembly qualified type name. GetType with the type name only will look for the Type in the caller's assembly and then in the System assembly. GetType with the assembly qualified type name will look for the Type in any assembly.

Type names may include trailing characters that denote additional information about the type, such as whether the type is a reference type, a pointer type or an array type. To retrieve the type name without these trailing characters, use t.GetElementType().ToString(), where t is the type.

Spaces are relevant in all type name components except the assembly name. In the assembly name, spaces before the ',' separator are relevant, but spaces after the ',' separator are ignored.

The name of a generic type ends with a backtick (`) followed by digits representing the number of generic type arguments. The purpose of this name mangling is to allow compilers to support generic types with the same name but with different numbers of type parameters, occurring in the same scope. For example, reflection returns the mangled names Tuple`1 and Tuple`2 from the generic methods Tuple(Of T) and Tuple(Of T0, T1) in Visual Basic, or Tuple<T> and Tuple<T0, T1> in Visual C#.

For generic types, the type argument list is enclosed in brackets, and the type arguments are separated by commas. For example, a generic Dictionary<TKey,TValue> has two type parameters. A Dictionary<TKey,TValue> of MyType with keys of type String might be represented as follows:

System.Collections.Generic.Dictionary`2[System.String,MyType]  

To specify an assembly-qualified type within a type argument list, enclose the assembly-qualified type within brackets. Otherwise, the commas that separate the parts of the assembly-qualified name are interpreted as delimiting additional type arguments. For example, a Dictionary<TKey,TValue> of MyType from MyAssembly.dll, with keys of type String, might be specified as follows:

Type.GetType("System.Collections.Generic.Dictionary`2[System.String,[MyType,MyAssembly]]")  

Note

An assembly-qualified type can be enclosed in brackets only when it appears within a type parameter list. The rules for searching assemblies for qualified and unqualified types in type parameter lists are the same as the rules for qualified and unqualified nongeneric types.

Nullable types are a special case of generic types. For example, a nullable Int32 is represented by the string "System.Nullable`1[System.Int32]".

Note

In C#, C++, and Visual Basic you can also get nullable types using type operators. For example, the nullable Boolean type is returned by typeof(Nullable<bool>) in C#, by Nullable<Boolean>::typeid in C++, and by GetType(Nullable(Of Boolean)) in Visual Basic.

The following table shows the syntax you use with GetType for various types.

To Get Use
A nullable Int32 Type.GetType("System.Nullable`1[System.Int32]")
An unmanaged pointer to MyType Type.GetType("MyType*")
An unmanaged pointer to a pointer to MyType Type.GetType("MyType**")
A managed pointer or reference to MyType Type.GetType("MyType&"). Note that unlike pointers, references are limited to one level.
A parent class and a nested class Type.GetType("MyParentClass+MyNestedClass")
A one-dimensional array with a lower bound of 0 Type.GetType("MyArray[]")
A one-dimensional array with an unknown lower bound Type.GetType("MyArray[*]")
An n-dimensional array A comma (,) inside the brackets a total of n-1 times. For example, System.Object[,,] represents a three-dimensional Object array.
A two-dimensional array's array Type.GetType("MyArray[][]")
A rectangular two-dimensional array with unknown lower bounds Type.GetType("MyArray[,]")
A generic type with one type argument Type.GetType("MyGenericType`1[MyType]")
A generic type with two type arguments Type.GetType("MyGenericType`2[MyType,AnotherType]")
A generic type with two assembly-qualified type arguments Type.GetType("MyGenericType`2[[MyType,MyAssembly],[AnotherType,AnotherAssembly]]")
An assembly-qualified generic type with an assembly-qualified type argument Type.GetType("MyGenericType`1[[MyType,MyAssembly]],MyGenericTypeAssembly")
A generic type whose type argument is a generic type with two type arguments Type.GetType("MyGenericType`1[AnotherGenericType`2[MyType,AnotherType]]")

See also

Applies to

GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>)

Gets the type with the specified name, optionally providing custom methods to resolve the assembly and the type.

public:
 static Type ^ GetType(System::String ^ typeName, Func<System::Reflection::AssemblyName ^, System::Reflection::Assembly ^> ^ assemblyResolver, Func<System::Reflection::Assembly ^, System::String ^, bool, Type ^> ^ typeResolver);
public static Type? GetType (string typeName, Func<System.Reflection.AssemblyName,System.Reflection.Assembly?>? assemblyResolver, Func<System.Reflection.Assembly?,string,bool,Type?>? typeResolver);
public static Type GetType (string typeName, Func<System.Reflection.AssemblyName,System.Reflection.Assembly> assemblyResolver, Func<System.Reflection.Assembly,string,bool,Type> typeResolver);
static member GetType : string * Func<System.Reflection.AssemblyName, System.Reflection.Assembly> * Func<System.Reflection.Assembly, string, bool, Type> -> Type
Public Shared Function GetType (typeName As String, assemblyResolver As Func(Of AssemblyName, Assembly), typeResolver As Func(Of Assembly, String, Boolean, Type)) As Type

Parameters

typeName
String

The name of the type to get. If the typeResolver parameter is provided, the type name can be any string that typeResolver is capable of resolving. If the assemblyResolver parameter is provided or if standard type resolution is used, typeName must be an assembly-qualified name (see AssemblyQualifiedName), unless the type is in the currently executing assembly or in mscorlib.dll/System.Private.CoreLib.dll, in which case it is sufficient to supply the type name qualified by its namespace.

assemblyResolver
Func<AssemblyName,Assembly>

A method that locates and returns the assembly that is specified in typeName. The assembly name is passed to assemblyResolver as an AssemblyName object. If typeName does not contain the name of an assembly, assemblyResolver is not called. If assemblyResolver is not supplied, standard assembly resolution is performed.

Caution Do not pass methods from unknown or untrusted callers. Doing so could result in elevation of privilege for malicious code. Use only methods that you provide or that you are familiar with.

typeResolver
Func<Assembly,String,Boolean,Type>

A method that locates and returns the type that is specified by typeName from the assembly that is returned by assemblyResolver or by standard assembly resolution. If no assembly is provided, the typeResolver method can provide one. The method also takes a parameter that specifies whether to perform a case-insensitive search; false is passed to that parameter.

Caution Do not pass methods from unknown or untrusted callers.

Returns

Type

The type with the specified name, or null if the type is not found.

Exceptions

typeName is null.

A class initializer is invoked and throws an exception.

An error occurs when typeName is parsed into a type name and an assembly name (for example, when the simple type name includes an unescaped special character).

-or-

typeName represents a generic type that has a pointer type, a ByRef type, or Void as one of its type arguments.

-or-

typeName represents a generic type that has an incorrect number of type arguments.

-or-

typeName represents a generic type, and one of its type arguments does not satisfy the constraints for the corresponding type parameter.

typeName represents an array of TypedReference.

The assembly or one of its dependencies was found, but could not be loaded.

-or-

typeName contains an invalid assembly name.

-or-

typeName is a valid assembly name without a type name.

The assembly or one of its dependencies is not valid.

-or-

The assembly was compiled with a later version of the common language runtime than the version that is currently loaded.

Remarks

Usage scenarios for this method and details about the assemblyResolver and typeResolver parameters can be found in the GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) method overload.

Note

If typeName cannot be found, the call to the GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>) method returns null. It does not throw an exception. To control whether an exception is thrown, call an overload of the GetType method that has a throwOnError parameter.

Calling this method overload is the same as calling the GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) method overload and specifying false for the throwOnError and ignoreCase parameters.

Applies to

GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean)

Gets the type with the specified name, specifying whether to throw an exception if the type is not found, and optionally providing custom methods to resolve the assembly and the type.

public:
 static Type ^ GetType(System::String ^ typeName, Func<System::Reflection::AssemblyName ^, System::Reflection::Assembly ^> ^ assemblyResolver, Func<System::Reflection::Assembly ^, System::String ^, bool, Type ^> ^ typeResolver, bool throwOnError);
public static Type? GetType (string typeName, Func<System.Reflection.AssemblyName,System.Reflection.Assembly?>? assemblyResolver, Func<System.Reflection.Assembly?,string,bool,Type?>? typeResolver, bool throwOnError);
public static Type GetType (string typeName, Func<System.Reflection.AssemblyName,System.Reflection.Assembly> assemblyResolver, Func<System.Reflection.Assembly,string,bool,Type> typeResolver, bool throwOnError);
static member GetType : string * Func<System.Reflection.AssemblyName, System.Reflection.Assembly> * Func<System.Reflection.Assembly, string, bool, Type> * bool -> Type
Public Shared Function GetType (typeName As String, assemblyResolver As Func(Of AssemblyName, Assembly), typeResolver As Func(Of Assembly, String, Boolean, Type), throwOnError As Boolean) As Type

Parameters

typeName
String

The name of the type to get. If the typeResolver parameter is provided, the type name can be any string that typeResolver is capable of resolving. If the assemblyResolver parameter is provided or if standard type resolution is used, typeName must be an assembly-qualified name (see AssemblyQualifiedName), unless the type is in the currently executing assembly or in mscorlib.dll/System.Private.CoreLib.dll, in which case it is sufficient to supply the type name qualified by its namespace.

assemblyResolver
Func<AssemblyName,Assembly>

A method that locates and returns the assembly that is specified in typeName. The assembly name is passed to assemblyResolver as an AssemblyName object. If typeName does not contain the name of an assembly, assemblyResolver is not called. If assemblyResolver is not supplied, standard assembly resolution is performed.

Caution Do not pass methods from unknown or untrusted callers. Doing so could result in elevation of privilege for malicious code. Use only methods that you provide or that you are familiar with.

typeResolver
Func<Assembly,String,Boolean,Type>

A method that locates and returns the type that is specified by typeName from the assembly that is returned by assemblyResolver or by standard assembly resolution. If no assembly is provided, the method can provide one. The method also takes a parameter that specifies whether to perform a case-insensitive search; false is passed to that parameter.

Caution Do not pass methods from unknown or untrusted callers.

throwOnError
Boolean

true to throw an exception if the type cannot be found; false to return null. Specifying false also suppresses some other exception conditions, but not all of them. See the Exceptions section.

Returns

Type

The type with the specified name. If the type is not found, the throwOnError parameter specifies whether null is returned or an exception is thrown. In some cases, an exception is thrown regardless of the value of throwOnError. See the Exceptions section.

Exceptions

typeName is null.

A class initializer is invoked and throws an exception.

throwOnError is true and the type is not found.

-or-

throwOnError is true and typeName contains invalid characters, such as an embedded tab.

-or-

throwOnError is true and typeName is an empty string.

-or-

throwOnError is true and typeName represents an array type with an invalid size.

-or-

typeName represents an array of TypedReference.

An error occurs when typeName is parsed into a type name and an assembly name (for example, when the simple type name includes an unescaped special character).

-or-

throwOnError is true and typeName contains invalid syntax (for example, "MyType[,*,]").

-or-

typeName represents a generic type that has a pointer type, a ByRef type, or Void as one of its type arguments.

-or-

typeName represents a generic type that has an incorrect number of type arguments.

-or-

typeName represents a generic type, and one of its type arguments does not satisfy the constraints for the corresponding type parameter.

throwOnError is true and the assembly or one of its dependencies was not found.

-or-

typeName contains an invalid assembly name.

-or-

typeName is a valid assembly name without a type name.

The assembly or one of its dependencies was found, but could not be loaded.

The assembly or one of its dependencies is not valid.

-or-

The assembly was compiled with a later version of the common language runtime than the version that is currently loaded.

Remarks

Usage scenarios for this method and details about the assemblyResolver and typeResolver parameters can be found in the GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) method overload.

Calling this method overload is the same as calling the GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean) method overload and specifying false for the ignoreCase parameter.

Applies to

GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean, Boolean)

Gets the type with the specified name, specifying whether to perform a case-sensitive search and whether to throw an exception if the type is not found, and optionally providing custom methods to resolve the assembly and the type.

public:
 static Type ^ GetType(System::String ^ typeName, Func<System::Reflection::AssemblyName ^, System::Reflection::Assembly ^> ^ assemblyResolver, Func<System::Reflection::Assembly ^, System::String ^, bool, Type ^> ^ typeResolver, bool throwOnError, bool ignoreCase);
public static Type? GetType (string typeName, Func<System.Reflection.AssemblyName,System.Reflection.Assembly?>? assemblyResolver, Func<System.Reflection.Assembly?,string,bool,Type?>? typeResolver, bool throwOnError, bool ignoreCase);
public static Type GetType (string typeName, Func<System.Reflection.AssemblyName,System.Reflection.Assembly> assemblyResolver, Func<System.Reflection.Assembly,string,bool,Type> typeResolver, bool throwOnError, bool ignoreCase);
static member GetType : string * Func<System.Reflection.AssemblyName, System.Reflection.Assembly> * Func<System.Reflection.Assembly, string, bool, Type> * bool * bool -> Type
Public Shared Function GetType (typeName As String, assemblyResolver As Func(Of AssemblyName, Assembly), typeResolver As Func(Of Assembly, String, Boolean, Type), throwOnError As Boolean, ignoreCase As Boolean) As Type

Parameters

typeName
String

The name of the type to get. If the typeResolver parameter is provided, the type name can be any string that typeResolver is capable of resolving. If the assemblyResolver parameter is provided or if standard type resolution is used, typeName must be an assembly-qualified name (see AssemblyQualifiedName), unless the type is in the currently executing assembly or in mscorlib.dll/System.Private.CoreLib.dll, in which case it is sufficient to supply the type name qualified by its namespace.

assemblyResolver
Func<AssemblyName,Assembly>

A method that locates and returns the assembly that is specified in typeName. The assembly name is passed to assemblyResolver as an AssemblyName object. If typeName does not contain the name of an assembly, assemblyResolver is not called. If assemblyResolver is not supplied, standard assembly resolution is performed.

Caution Do not pass methods from unknown or untrusted callers. Doing so could result in elevation of privilege for malicious code. Use only methods that you provide or that you are familiar with.

typeResolver
Func<Assembly,String,Boolean,Type>

A method that locates and returns the type that is specified by typeName from the assembly that is returned by assemblyResolver or by standard assembly resolution. If no assembly is provided, the method can provide one. The method also takes a parameter that specifies whether to perform a case-insensitive search; the value of ignoreCase is passed to that parameter.

Caution Do not pass methods from unknown or untrusted callers.

throwOnError
Boolean

true to throw an exception if the type cannot be found; false to return null. Specifying false also suppresses some other exception conditions, but not all of them. See the Exceptions section.

ignoreCase
Boolean

true to perform a case-insensitive search for typeName, false to perform a case-sensitive search for typeName.

Returns

Type

The type with the specified name. If the type is not found, the throwOnError parameter specifies whether null is returned or an exception is thrown. In some cases, an exception is thrown regardless of the value of throwOnError. See the Exceptions section.

Exceptions

typeName is null.

A class initializer is invoked and throws an exception.

throwOnError is true and the type is not found.

-or-

throwOnError is true and typeName contains invalid characters, such as an embedded tab.

-or-

throwOnError is true and typeName is an empty string.

-or-

throwOnError is true and typeName represents an array type with an invalid size.

-or-

typeName represents an array of TypedReference.

An error occurs when typeName is parsed into a type name and an assembly name (for example, when the simple type name includes an unescaped special character).

-or-

throwOnError is true and typeName contains invalid syntax (for example, "MyType[,*,]").

-or-

typeName represents a generic type that has a pointer type, a ByRef type, or Void as one of its type arguments.

-or-

typeName represents a generic type that has an incorrect number of type arguments.

-or-

typeName represents a generic type, and one of its type arguments does not satisfy the constraints for the corresponding type parameter.

throwOnError is true and the assembly or one of its dependencies was not found.

The assembly or one of its dependencies was found, but could not be loaded.

-or-

typeName contains an invalid assembly name.

-or-

typeName is a valid assembly name without a type name.

The assembly or one of its dependencies is not valid.

-or-

The assembly was compiled with a later version of the common language runtime than the version that is currently loaded.

Remarks

Use this method overload and its associated overloads (GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>) and GetType(String, Func<AssemblyName,Assembly>, Func<Assembly,String,Boolean,Type>, Boolean)) to replace the default implementation of the GetType method with more flexible implementations. By providing your own methods that resolve type names and the names of the assemblies that contain them, you can do the following:

  • Control which version of an assembly a type is loaded from.

  • Provide another place to look for a type name that does not include an assembly name.

  • Load assemblies using partial assembly names.

  • Return subclasses of System.Type that are not created by the common language runtime (CLR).

For example, in version-tolerant serialization this method enables you to search for a "best fit" assembly by using a partial name. Other overloads of the GetType method require an assembly-qualified type name, which includes the version number.

Alternate implementations of the type system may need to return subclasses of System.Type that are not created by the CLR; all types that are returned by other overloads of the GetType method are runtime types.

Usage Notes

This method overload and its associated overloads parse typeName into the name of a type and the name of an assembly, and then resolve the names. Resolution of the assembly name occurs before resolution of the type name, because a type name must be resolved in the context of an assembly.

Note

If you are unfamiliar with the concept of assembly-qualified type names, see the AssemblyQualifiedName property.

If typeName is not an assembly-qualified name, assembly resolution is skipped. Unqualified type names can be resolved in the context of mscorlib.dll/System.Private.CoreLib.dll or the currently executing assembly, or you can optionally provide an assembly in the typeResolver parameter. The effects of including or omitting the assembly name for different kinds of name resolution are displayed as a table in the Mixed Name Resolution section.

General usage notes:

  • Do not pass methods to assemblyResolver or typeResolver if they come from unknown or untrusted callers. Use only methods that you provide or that you are familiar with.

    Caution

    Using methods from unknown or untrusted callers could result in elevation of privilege for malicious code.

  • If you omit the assemblyResolver and/or typeResolver parameters, the value of the throwOnError parameter is passed to the methods that perform the default resolution.

  • If throwOnError is true, this method throws a TypeLoadException when typeResolver returns null, and a FileNotFoundException when assemblyResolver returns null.

  • This method does not catch exceptions thrown by assemblyResolver and typeResolver. You are responsible for any exceptions that are thrown by the resolver methods.

Resolving Assemblies

The assemblyResolver method receives an AssemblyName object, which is produced by parsing the string assembly name that is included in typeName. If typeName does not contain an assembly name, assemblyResolver is not called and null is passed to typeResolver.

If assemblyResolver is not supplied, standard assembly probing is used to locate the assembly. If assemblyResolver is provided, the GetType method does not do standard probing; in that case you must ensure that your assemblyResolver can handle all the assemblies you pass to it.

The assemblyResolver method should return null if the assembly cannot be resolved. If assemblyResolver returns null, typeResolver is not called and no further processing occurs; additionally, if throwOnError is true, a FileNotFoundException is thrown.

If the AssemblyName that is passed to assemblyResolver is a partial name, one or more of its parts are null. For example, if it has no version, the Version property is null. If the Version property, the CultureInfo property, and the GetPublicKeyToken method all return null, then only the simple name of the assembly was supplied. The assemblyResolver method can use or ignore all parts of the assembly name.

The effects of different assembly resolution options are displayed as a table in the Mixed Name Resolution section, for simple and assembly-qualified type names.

Resolving Types

If typeName does not specify an assembly name, typeResolver is always called. If typeName specifies an assembly name, typeResolver is called only when the assembly name is successfully resolved. If assemblyResolver or standard assembly probing returns null, typeResolver is not called.

The typeResolver method receives three arguments:

  • The assembly to search or null if typeName does not contain an assembly name.

  • The simple name of the type. In the case of a nested type, this is the outermost containing type. In the case of a generic type, this is the simple name of the generic type.

  • A Boolean value that is true if the case of type names is to be ignored.

The implementation determines the way these arguments are used. The typeResolver method should return null if it cannot resolve the type. If typeResolver returns null and throwOnError is true, this overload of GetType throws a TypeLoadException.

The effects of different type resolution options are displayed as a table in the Mixed Name Resolution section, for simple and assembly-qualified type names.

Resolving Nested Types

If typeName is a nested type, only the name of the outermost containing type is passed to typeResolver. When typeResolver returns this type, the GetNestedType method is called recursively until the innermost nested type has been resolved.

Resolving Generic Types

The GetType is called recursively to resolve generic types: First to resolve the generic type itself, and then to resolve its type arguments. If a type argument is generic, GetType is called recursively to resolve its type arguments, and so on.

The combination of assemblyResolver and typeResolver that you provide must be capable of resolving all levels of this recursion. For example, suppose you supply an assemblyResolver that controls the loading of MyAssembly. Suppose you want to resolve the generic type Dictionary<string, MyType> (Dictionary(Of String, MyType) in Visual Basic). You might pass the following generic type name:

"System.Collections.Generic.Dictionary`2[System.String,[MyNamespace.MyType, MyAssembly]]"  

Notice that MyType is the only assembly-qualified type argument. The names of the Dictionary<TKey,TValue> and String classes are not assembly-qualified. Your typeResolver must be able handle either an assembly or null, because it will receive null for Dictionary<TKey,TValue> and String. It can handle that case by calling an overload of the GetType method that takes a string, because both of the unqualified type names are in mscorlib.dll/System.Private.CoreLib.dll:

Type t = Type.GetType(test,
                      (aName) => aName.Name == "MyAssembly" ?
                          Assembly.LoadFrom(@".\MyPath\v5.0\MyAssembly.dll") : null,
                      (assem, name, ignore) => assem == null ?
                          Type.GetType(name, false, ignore) :
                              assem.GetType(name, false, ignore)
                     );
let t =
    Type.GetType(test,
        (fun aName ->
            if aName.Name = "MyAssembly" then
                Assembly.LoadFrom @".\MyPath\v5.0\MyAssembly.dll"
            else null),
        fun assem name ignr ->
            if assem = null then
                Type.GetType(name, false, ignr)
            else
                assem.GetType(name, false, ignr))

The assemblyResolver method is not called for the dictionary type and the string type, because those type names are not assembly-qualified.

Now suppose that instead of System.String, the first generic argument type is YourType, from YourAssembly:

"System.Collections.Generic.Dictionary`2[[YourNamespace.YourType, YourAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], [MyNamespace.MyType, MyAssembly]]"  

Because this assembly is neither mscorlib.dll/System.Private.CoreLib.dll nor the currently executing assembly, you cannot resolve YourType without an assembly-qualified name. Because your assemblyResolve will be called recursively, it must be able to handle this case. Instead of returning null for assemblies other than MyAssembly, it now performs an assembly load using the supplied AssemblyName object.

Type t2 = Type.GetType(test,
                       (aName) => aName.Name == "MyAssembly" ?
                           Assembly.LoadFrom(@".\MyPath\v5.0\MyAssembly.dll") :
                           Assembly.Load(aName),
                       (assem, name, ignore) => assem == null ?
                           Type.GetType(name, false, ignore) :
                               assem.GetType(name, false, ignore), true
                      );
let t2 =
    Type.GetType(test,
        (fun aName ->
            if aName.Name = "MyAssembly" then
                Assembly.LoadFrom @".\MyPath\v5.0\MyAssembly.dll"
            else Assembly.Load aName),
        (fun assem name ignr ->
            if assem = null then
                Type.GetType(name, false, ignr)
            else
                assem.GetType(name, false, ignr)), true)

Back to Usage Notes.

Resolving Type Names with Special Characters

Certain characters have special meanings in assembly-qualified names. If a simple type name contains these characters, the characters cause parsing errors when the simple name is part of an assembly-qualified name. To avoid the parsing errors, you must escape the special characters with a backslash before you can pass the assembly-qualified name to the GetType method. For example, if a type is named Strange]Type, the escape character must be added ahead of the square bracket as follows: Strange\]Type.

Note

Names with such special characters cannot be created in Visual Basic or C#, but can be created by using Microsoft intermediate language (MSIL) or by emitting dynamic assemblies.

The following table shows the special characters for type names.

Character Meaning
, (comma) Delimiter for assembly-qualified names.
[] (square brackets) As a suffix pair, indicates an array type; as a delimiter pair, encloses generic argument lists and assembly-qualified names.
& (ampersand) As a suffix, indicates that a type is a reference type.
* (asterisk) As a suffix, indicates that a type is a pointer type.
+ (plus) Delimiter for nested types.
\ (backslash) Escape character.

Properties such as AssemblyQualifiedName return correctly escaped strings. You must pass correctly escaped strings to the GetType method. In turn, the GetType method passes correctly escaped names to typeResolver and to the default type resolution methods. If you need to compare a name to an unescaped name in typeResolver, you must remove the escape characters.

Back to Usage Notes.

Mixed Name Resolution

The following table summarizes the interactions between assemblyResolver, typeResolver, and default name resolution, for all combinations of type name and assembly name in typeName:

Contents of type name Assembly resolver method Type resolver method Result
type, assembly null null Equivalent to calling the Type.GetType(String, Boolean, Boolean) method overload.
type, assembly provided null assemblyResolver returns the assembly or returns null if it cannot resolve the assembly. If the assembly is resolved, the Assembly.GetType(String, Boolean, Boolean) method overload is used to load the type from the assembly; otherwise, there is no attempt to resolve the type.
type, assembly null provided Equivalent to converting the assembly name to an AssemblyName object and calling the Assembly.Load(AssemblyName) method overload to get the assembly. If the assembly is resolved, it is passed to typeResolver; otherwise, typeResolver is not called and there is no further attempt to resolve the type.
type, assembly provided provided assemblyResolver returns the assembly or returns null if it cannot resolve the assembly. If the assembly is resolved, it is passed to typeResolver; otherwise, typeResolver is not called and there is no further attempt to resolve the type.
type null, provided null Equivalent to calling the Type.GetType(String, Boolean, Boolean) method overload. Because the assembly name is not provided, only mscorlib.dll/System.Private.CoreLib.dll and the currently executing assembly are searched. If assemblyResolver is provided, it is ignored.
type null, provided provided typeResolver is called, and null is passed for the assembly. typeResolver can provide a type from any assembly, including assemblies it loads for the purpose. If assemblyResolver is provided, it is ignored.
assembly null, provided null, provided A FileLoadException is thrown, because the assembly name is parsed as if it were an assembly-qualified type name. This results in an invalid assembly name.

Back to: Usage Notes, Resolving Assemblies, Resolving Types.

Applies to