Activator.​Create​Instance Method

Definition

Overloads

Create​Instance(​App​Domain, ​String, ​String, ​Boolean, ​Binding​Flags, ​Binder, ​Object[], ​Culture​Info, ​Object[], ​Evidence)

Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and the constructor that best matches the specified parameters.

Create​Instance(​App​Domain, ​String, ​String, ​Boolean, ​Binding​Flags, ​Binder, ​Object[], ​Culture​Info, ​Object[])

Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and the constructor that best matches the specified parameters.

Create​Instance(​String, ​String, ​Boolean, ​Binding​Flags, ​Binder, ​Object[], ​Culture​Info, ​Object[])

Creates an instance of the type whose name is specified, using the named assembly and the constructor that best matches the specified parameters.

Create​Instance(​Type, ​Binding​Flags, ​Binder, ​Object[], ​Culture​Info, ​Object[])

Creates an instance of the specified type using the constructor that best matches the specified parameters.

Create​Instance(​Type, ​Binding​Flags, ​Binder, ​Object[], ​Culture​Info)

Creates an instance of the specified type using the constructor that best matches the specified parameters.

Create​Instance(​Type, ​Object[], ​Object[])

Creates an instance of the specified type using the constructor that best matches the specified parameters.

Create​Instance(​String, ​String, ​Object[])

Creates an instance of the type whose name is specified, using the named assembly and default constructor.

Create​Instance(​String, ​String, ​Boolean, ​Binding​Flags, ​Binder, ​Object[], ​Culture​Info, ​Object[], ​Evidence)

Creates an instance of the type whose name is specified, using the named assembly and the constructor that best matches the specified parameters.

Create​Instance(​Type, ​Object[])

Creates an instance of the specified type using the constructor that best matches the specified parameters.

Create​Instance(​Type, ​Boolean)

Creates an instance of the specified type using that type's default constructor.

Create​Instance(​String, ​String)

Creates an instance of the type whose name is specified, using the named assembly and default constructor.

Create​Instance(​Activation​Context, ​String[])

Creates an instance of the type that is designated by the specified ActivationContext object and activated with the specified custom activation data.

Create​Instance(​Type)

Creates an instance of the specified type using that type's default constructor.

Create​Instance(​Activation​Context)

Creates an instance of the type designated by the specified ActivationContext object.

Create​Instance(​App​Domain, ​String, ​String)

Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and default constructor.

Create​Instance<​T>()

Creates an instance of the type designated by the specified generic type parameter, using the parameterless constructor.

CreateInstance(AppDomain, String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence)

Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and the constructor that best matches the specified parameters.

[System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
[System.Security.SecurityCritical]
public static System.Runtime.Remoting.ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes, System.Security.Policy.Evidence securityAttributes);
Parameters
domain
AppDomain

The domain where the type named typeName is created.

assemblyName
String

The name of the assembly where the type named typeName is sought. If assemblyName is null, the executing assembly is searched.

typeName
String

The fully qualified name of the preferred type.

ignoreCase
Boolean

true to specify that the search for typeName is not case-sensitive; false to specify that the search is case-sensitive.

bindingAttr
BindingFlags

A combination of zero or more bit flags that affect the search for the typeName constructor. If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder

An object that uses bindingAttr and args to seek and identify the typeName constructor. If binder is null, the default binder is used.

args
System.Object[]

An array of arguments that match in number, order, and type the parameters of the constructor to invoke. If args is an empty array or null, the constructor that takes no parameters (the default constructor) is invoked.

culture
CultureInfo

Culture-specific information that governs the coercion of args to the formal types declared for the typeName constructor. If culture is null, the CultureInfo for the current thread is used.

activationAttributes
System.Object[]

An array of one or more attributes that can participate in activation. This is typically an array that contains a single UrlAttribute object. The UrlAttribute specifies the URL that is required to activate a remote object.

securityAttributes
Evidence

Information used to make security policy decisions and grant code permissions.

Returns

A handle that must be unwrapped to access the newly created instance.

Attributes
Exceptions

domain or typeName is null.

No matching constructor was found.

typename was not found in assemblyName.

assemblyName was not found.

The caller does not have permission to call this constructor.

Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

The constructor, which was invoked through reflection, threw an exception.

The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or-

activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject.

-or-

The constructor that best matches args has varargs arguments.

assemblyName is not a valid assembly.

-or-

The common language runtime (CLR) version 2.0 or later is currently loaded, and assemblyName was compiled for a version of the CLR that is later than the currently loaded version. Note that the .NET Framework versions 2.0, 3.0, and 3.5 all use CLR version 2.0.

An assembly or module was loaded twice with two different evidences.

-or-

The assembly name or code base is invalid.

Remarks

Use CreateInstance when a host needs to execute code in an application domain that has restricted security permissions.

Use System.Runtime.Remoting.ObjectHandle.Unwrap to unwrap the return value.

Note

This method uses System.Security.Permissions.SecurityAction to require the immediate caller to have full trust.

CreateInstance(AppDomain, String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and the constructor that best matches the specified parameters.

[System.Security.SecurityCritical]
public static System.Runtime.Remoting.ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes);
Parameters
domain
AppDomain

The domain where the type named typeName is created.

assemblyName
String

The name of the assembly where the type named typeName is sought. If assemblyName is null, the executing assembly is searched.

typeName
String

The fully qualified name of the preferred type.

ignoreCase
Boolean

true to specify that the search for typeName is not case-sensitive; false to specify that the search is case-sensitive.

bindingAttr
BindingFlags

A combination of zero or more bit flags that affect the search for the typeName constructor. If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder

An object that uses bindingAttr and args to seek and identify the typeName constructor. If binder is null, the default binder is used.

args
System.Object[]

An array of arguments that match in number, order, and type the parameters of the constructor to invoke. If args is an empty array or null, the constructor that takes no parameters (the default constructor) is invoked.

culture
CultureInfo

Culture-specific information that governs the coercion of args to the formal types declared for the typeName constructor. If culture is null, the CultureInfo for the current thread is used.

activationAttributes
System.Object[]

An array of one or more attributes that can participate in activation. This is typically an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

This parameter is related to client-activated objects. Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. Distributed applications should instead use Windows Communication Foundation.

Returns

A handle that must be unwrapped to access the newly created instance.

Attributes
Exceptions

domain or typeName is null.

No matching constructor was found.

typename was not found in assemblyName.

assemblyName was not found.

The caller does not have permission to call this constructor.

Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

The constructor, which was invoked through reflection, threw an exception.

The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or-

activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject.

-or-

The constructor that best matches args has varargs arguments.

assemblyName is not a valid assembly.

-or-

The common language runtime (CLR) version 2.0 or later is currently loaded, and assemblyName was compiled for a version of the CLR that is later than the currently loaded version. Note that the .NET Framework versions 2.0, 3.0, and 3.5 all use CLR version 2.0.

An assembly or module was loaded twice with two different evidences.

-or-

The assembly name or code base is invalid.

Remarks

Use CreateInstance when a host needs to execute code in an application domain that has restricted security permissions.

Use System.Runtime.Remoting.ObjectHandle.Unwrap to unwrap the return value.

Note

This method uses System.Security.Permissions.SecurityAction to require the immediate caller to have full trust.

CreateInstance(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

Creates an instance of the type whose name is specified, using the named assembly and the constructor that best matches the specified parameters.

public static System.Runtime.Remoting.ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes);
Parameters
assemblyName
String

The name of the assembly where the type named typeName is sought. If assemblyName is null, the executing assembly is searched.

typeName
String

The fully qualified name of the preferred type.

ignoreCase
Boolean

true to specify that the search for typeName is not case-sensitive; false to specify that the search is case-sensitive.

bindingAttr
BindingFlags

A combination of zero or more bit flags that affect the search for the typeName constructor. If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder

An object that uses bindingAttr and args to seek and identify the typeName constructor. If binder is null, the default binder is used.

args
System.Object[]

An array of arguments that match in number, order, and type the parameters of the constructor to invoke. If args is an empty array or null, the constructor that takes no parameters (the default constructor) is invoked.

culture
CultureInfo

Culture-specific information that governs the coercion of args to the formal types declared for the typeName constructor. If culture is null, the CultureInfo for the current thread is used.

activationAttributes
System.Object[]

An array of one or more attributes that can participate in activation. This is typically an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

This parameter is related to client-activated objects. Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. Distributed applications should instead use Windows Communication Foundation.

Returns

A handle that must be unwrapped to access the newly created instance.

Exceptions

typeName is null.

No matching constructor was found.

typename was not found in assemblyName.

assemblyName was not found.

The caller does not have permission to call this constructor.

Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

The constructor, which was invoked through reflection, threw an exception.

The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or-

activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject.

-or-

The constructor that best matches args has varargs arguments.

assemblyName is not a valid assembly.

-or-

The common language runtime (CLR) version 2.0 or later is currently loaded, and assemblyName was compiled for a version of the CLR that is later than the currently loaded version. Note that the .NET Framework versions 2.0, 3.0, and 3.5 all use CLR version 2.0.

An assembly or module was loaded twice with two different evidences.

-or-

The assembly name or code base is invalid.

Remarks

Use System.Runtime.Remoting.ObjectHandle.Unwrap to unwrap the return value.

Note

Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to create nonpublic types and members if the caller has been granted ReflectionPermission with the System.Security.Permissions.ReflectionPermissionFlag flag and if the grant set of the assembly that contains the nonpublic types and members is restricted to the caller’s grant set or to a subset thereof. (See Security Considerations for Reflection42d9dc2a-8fcc-4ff3-b002-4ff260ef3dc5.)

To use this functionality, your application should target the .NET Framework 3.5 or later.

CreateInstance(Type, BindingFlags, Binder, Object[], CultureInfo, Object[])

Creates an instance of the specified type using the constructor that best matches the specified parameters.

public static object CreateInstance (Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes);
Parameters
type
Type

The type of object to create.

bindingAttr
BindingFlags

A combination of zero or more bit flags that affect the search for the type constructor. If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder

An object that uses bindingAttr and args to seek and identify the type constructor. If binder is null, the default binder is used.

args
System.Object[]

An array of arguments that match in number, order, and type the parameters of the constructor to invoke. If args is an empty array or null, the constructor that takes no parameters (the default constructor) is invoked.

culture
CultureInfo

Culture-specific information that governs the coercion of args to the formal types declared for the type constructor. If culture is null, the CultureInfo for the current thread is used.

activationAttributes
System.Object[]

An array of one or more attributes that can participate in activation. This is typically an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

This parameter is related to client-activated objects. Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. Distributed applications should instead use Windows Communication Foundation.

Returns

A reference to the newly created object.

Exceptions

type is null.

type is not a RuntimeType.

-or-

type is an open generic type (that is, the ContainsGenericParameters property returns true).

type cannot be a TypeBuilder.

-or-

Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or-

activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject.

-or-

The assembly that contains type is a dynamic assembly that was created with Save.

-or-

The constructor that best matches args has varargs arguments.

The constructor being called throws an exception.

The caller does not have permission to call this constructor.

Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

No matching constructor was found.

type is a COM object but the class identifier used to obtain the type is invalid, or the identified class is not registered.

type is not a valid type.

Remarks

The constructor to be invoked must provide the most specific match with the specified argument list under the constraints of the specified binder and binding attributes.

Note

Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types and members if the caller has been granted ReflectionPermission with the System.Security.Permissions.ReflectionPermissionFlag flag and if the grant set of the nonpublic types and members is restricted to the caller’s grant set or to a subset thereof. (See Security Considerations for Reflection.)

To use this functionality, your application should target the .NET Framework 3.5 or later.

CreateInstance(Type, BindingFlags, Binder, Object[], CultureInfo)

Creates an instance of the specified type using the constructor that best matches the specified parameters.

public static object CreateInstance (Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture);
Parameters
type
Type

The type of object to create.

bindingAttr
BindingFlags

A combination of zero or more bit flags that affect the search for the type constructor. If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder

An object that uses bindingAttr and args to seek and identify the type constructor. If binder is null, the default binder is used.

args
System.Object[]

An array of arguments that match in number, order, and type the parameters of the constructor to invoke. If args is an empty array or null, the constructor that takes no parameters (the default constructor) is invoked.

culture
CultureInfo

Culture-specific information that governs the coercion of args to the formal types declared for the type constructor. If culture is null, the CultureInfo for the current thread is used.

Returns

A reference to the newly created object.

Exceptions

type is null.

type is not a RuntimeType.

-or-

type is an open generic type (that is, the ContainsGenericParameters property returns true).

type cannot be a TypeBuilder.

-or-

Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or-

The assembly that contains type is a dynamic assembly that was created with Save.

-or-

The constructor that best matches args has varargs arguments.

The constructor being called throws an exception.

The caller does not have permission to call this constructor.

Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

No matching constructor was found.

type is a COM object but the class identifier used to obtain the type is invalid, or the identified class is not registered.

type is not a valid type.

Remarks

The constructor to be invoked must provide the most specific match with the specified argument list under the constraints of the specified binder and binding attributes.

Note

Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types and members if the caller has been granted ReflectionPermission with the System.Security.Permissions.ReflectionPermissionFlag flag and if the grant set of the assembly that contains the nonpublic types and members is restricted to the caller’s grant set or to a subset thereof. (See Security Considerations for Reflection.)

To use this functionality, your application should target the .NET Framework 3.5 or later.

CreateInstance(Type, Object[], Object[])

Creates an instance of the specified type using the constructor that best matches the specified parameters.

public static object CreateInstance (Type type, object[] args, object[] activationAttributes);
Parameters
type
Type

The type of object to create.

args
System.Object[]

An array of arguments that match in number, order, and type the parameters of the constructor to invoke. If args is an empty array or null, the constructor that takes no parameters (the default constructor) is invoked.

activationAttributes
System.Object[]

An array of one or more attributes that can participate in activation. This is typically an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

This parameter is related to client-activated objects. Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. Distributed applications should instead use Windows Communication Foundation.

Returns

A reference to the newly created object.

Exceptions

type is null.

type is not a RuntimeType.

-or-

type is an open generic type (that is, the ContainsGenericParameters property returns true).

type cannot be a TypeBuilder.

-or-

Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or-

activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject.

-or-

The assembly that contains type is a dynamic assembly that was created with Save.

-or-

The constructor that best matches args has varargs arguments.

The constructor being called throws an exception.

The caller does not have permission to call this constructor.

Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

No matching public constructor was found.

type is a COM object but the class identifier used to obtain the type is invalid, or the identified class is not registered.

type is not a valid type.

Remarks

The constructor to be invoked must be accessible and must provide the most specific match with the specified argument list.

Note

Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types if the caller has been granted ReflectionPermission with the System.Security.Permissions.ReflectionPermissionFlag flag and if the grant set of the assembly that contains the nonpublic types is restricted to the caller’s grant set or to a subset thereof. (See Security Considerations for Reflection.)

To use this functionality, your application should target the .NET Framework 3.5 or later.

CreateInstance(String, String, Object[])

Creates an instance of the type whose name is specified, using the named assembly and default constructor.

public static System.Runtime.Remoting.ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes);
Parameters
assemblyName
String

The name of the assembly where the type named typeName is sought. If assemblyName is null, the executing assembly is searched.

typeName
String

The fully qualified name of the preferred type.

activationAttributes
System.Object[]

An array of one or more attributes that can participate in activation. This is typically an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

This parameter is related to client-activated objects. Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. Distributed applications should instead use Windows Communication Foundation.

Returns

A handle that must be unwrapped to access the newly created instance.

Exceptions

typeName is null.

No matching public constructor was found.

typename was not found in assemblyName.

assemblyName was not found.

The caller does not have permission to call this constructor.

Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or-

activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject.

-or-

activationAttributes is not a UrlAttribute

array.

assemblyName is not a valid assembly.

-or-

The common language runtime (CLR) version 2.0 or later is currently loaded, and assemblyName was compiled for a version of the CLR that is later than the currently loaded version. Note that the .NET Framework versions 2.0, 3.0, and 3.5 all use CLR version 2.0.

An assembly or module was loaded twice with two different evidences.

-or-

The assembly name or code base is invalid.

An error occurred when attempting remote activation in a target specified in activationAttributes.

Remarks

Use System.Runtime.Remoting.ObjectHandle.Unwrap to unwrap the return value.

Note

Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to create nonpublic types if the caller has been granted ReflectionPermission with the System.Security.Permissions.ReflectionPermissionFlag flag and if the grant set of the nonpublic types is restricted to the caller’s grant set or to a subset thereof. (See Security Considerations for Reflection.)

To use this functionality, your application should target the .NET Framework 3.5 or later.

CreateInstance(String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[], Evidence)

Creates an instance of the type whose name is specified, using the named assembly and the constructor that best matches the specified parameters.

[System.Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public static System.Runtime.Remoting.ObjectHandle CreateInstance (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes, System.Security.Policy.Evidence securityInfo);
Parameters
assemblyName
String

The name of the assembly where the type named typeName is sought. If assemblyName is null, the executing assembly is searched.

typeName
String

The fully qualified name of the preferred type.

ignoreCase
Boolean

true to specify that the search for typeName is not case-sensitive; false to specify that the search is case-sensitive.

bindingAttr
BindingFlags

A combination of zero or more bit flags that affect the search for the typeName constructor. If bindingAttr is zero, a case-sensitive search for public constructors is conducted.

binder
Binder

An object that uses bindingAttr and args to seek and identify the typeName constructor. If binder is null, the default binder is used.

args
System.Object[]

An array of arguments that match in number, order, and type the parameters of the constructor to invoke. If args is an empty array or null, the constructor that takes no parameters (the default constructor) is invoked.

culture
CultureInfo

Culture-specific information that governs the coercion of args to the formal types declared for the typeName constructor. If culture is null, the CultureInfo for the current thread is used.

activationAttributes
System.Object[]

An array of one or more attributes that can participate in activation. This is typically an array that contains a single UrlAttribute object that specifies the URL that is required to activate a remote object.

This parameter is related to client-activated objects. Client activation is a legacy technology that is retained for backward compatibility but is not recommended for new development. Distributed applications should instead use Windows Communication Foundation.

securityInfo
Evidence

Information used to make security policy decisions and grant code permissions.

Returns

A handle that must be unwrapped to access the newly created instance.

Attributes
Exceptions

typeName is null.

No matching constructor was found.

typename was not found in assemblyName.

assemblyName was not found.

The caller does not have permission to call this constructor.

Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

The constructor, which was invoked through reflection, threw an exception.

The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or-

activationAttributes is not an empty array, and the type being created does not derive from MarshalByRefObject.

-or-

The constructor that best matches args has varargs arguments.

assemblyName is not a valid assembly.

-or-

The common language runtime (CLR) version 2.0 or later is currently loaded, and assemblyName was compiled for a version of the CLR that is later than the currently loaded version. Note that the .NET Framework versions 2.0, 3.0, and 3.5 all use CLR version 2.0.

An assembly or module was loaded twice with two different evidences.

-or-

The assembly name or code base is invalid.

Remarks

Use System.Runtime.Remoting.ObjectHandle.Unwrap to unwrap the return value.

Note

Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to create nonpublic types and members if the caller has been granted ReflectionPermission with the System.Security.Permissions.ReflectionPermissionFlag flag and if the grant set of the assembly that contains the nonpublic types and members is restricted to the caller’s grant set or to a subset thereof. (See Security Considerations for Reflection.)

To use this functionality, your application should target the .NET Framework 3.5 or later.

CreateInstance(Type, Object[])

Creates an instance of the specified type using the constructor that best matches the specified parameters.

public static object CreateInstance (Type type, object[] args);
Parameters
type
Type

The type of object to create.

args
System.Object[]

An array of arguments that match in number, order, and type the parameters of the constructor to invoke. If args is an empty array or null, the constructor that takes no parameters (the default constructor) is invoked.

Returns

A reference to the newly created object.

Exceptions

type is null.

type is not a RuntimeType.

-or-

type is an open generic type (that is, the ContainsGenericParameters property returns true).

type cannot be a TypeBuilder.

-or-

Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or-

The assembly that contains type is a dynamic assembly that was created with Save.

-or-

The constructor that best matches args has varargs arguments.

The constructor being called throws an exception.

In the [.NET for Windows Store apps](http://go.microsoft.com/fwlink/?LinkID=247912) or the [Portable Class Library](~/docs/standard/cross-platform/cross-platform-development-with-the-portable-class-library.md), catch the base class exception, MemberAccessException, instead.

The caller does not have permission to call this constructor.

Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

In the [.NET for Windows Store apps](http://go.microsoft.com/fwlink/?LinkID=247912) or the [Portable Class Library](~/docs/standard/cross-platform/cross-platform-development-with-the-portable-class-library.md), catch the base class exception, MissingMemberException, instead.

No matching public constructor was found.

type is a COM object but the class identifier used to obtain the type is invalid, or the identified class is not registered.

type is not a valid type.

Examples

The following example calls the CreateInstance(Type, Object[]) method to create a String object. It calls the System.String.String(Char[], Int32, Int32) constructor to instantiate a string that contains ten elements from a character array starting at the fourteenth position.

using System;

public class Example
{
   public static void Main()
   {
      // Initialize array of characters from a to z.
      Char[] chars = new Char[26]; 
      for (int ctr = 0; ctr < 26; ctr++)
         chars[ctr] = (char) (ctr + 0x0061);

      Object obj = Activator.CreateInstance(typeof(String),
                                            new Object[] { chars, 13, 10 } );
      Console.WriteLine(obj);                                          
   }
}
// The example displays the following output:
//       nopqrstuvw
Module Example
   Public Sub Main()
      ' Initialize array of characters from a to z.
      Dim chars(25) As Char 
      For ctr As Short = 0 To 25
         chars(ctr) = ChrW(ctr + &h0061)
      Next 
      Dim obj As Object = Activator.CreateInstance(GetType(String),
                                                   { chars, 13, 10 })
      Console.WriteLine(obj)                                          
   End Sub
End Module
' The example displays the following output:
'       nopqrstuvw

The following example creates a jagged array whose elements are arguments to be passed to a String constructor. The example then passes each array to the CreateInstance(Type, Object[]) method to invoke the appropriate string constructor.

using System;

public class Example
{
   public static void Main()
   {
      char[] characters = { 'a', 'b', 'c', 'd', 'e', 'f' };
      object[][] arguments = new object[3][] { new object[] { characters },
                                               new object[] { characters, 1, 4 },
                                               new object[] { characters[1], 20 } };

      for (int ctr = 0; ctr <= arguments.GetUpperBound(0); ctr++) {
         object[] args = arguments[ctr];
         object result = Activator.CreateInstance(typeof(String), args);
         Console.WriteLine("{0}: {1}", result.GetType().Name, result);
      }
   }
}
// The example displays the following output:
//    String: abcdef
//    String: bcde
//    String: bbbbbbbbbbbbbbbbbbbb
Module Example
   Public Sub Main()
      Dim characters() As Char = { "a"c, "b"c, "c"c, "d"c, "e"c, "f"c }
      Dim arguments()() As Object = new Object(2)() { New Object() { characters },
                                                      New Object() { characters, 1, 4 },
                                                      New Object() { characters(1), 20 } }

      For ctr As Integer = 0 To arguments.GetUpperBound(0)
         Dim args() As Object = arguments(ctr)
         Dim result As Object = Activator.CreateInstance(GetType(String), args)
         Console.WriteLine("{0}: {1}", result.GetType().Name, result)
      Next
   End Sub
End Module
' The example displays the following output:
'       String: abcdef
'       String: bcde
'       String: bbbbbbbbbbbbbbbbbbbb

Remarks

The constructor to be invoked must be accessible and must provide the most specific match with the specified argument list.

Note

Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types if the caller has been granted ReflectionPermission with the System.Security.Permissions.ReflectionPermissionFlag flag and if the grant set of the assembly that contains the nonpublic types is restricted to the caller’s grant set or to a subset thereof. (See Security Considerations for Reflection.)

To use this functionality, your application should target the .NET Framework 3.5 or later.

CreateInstance(Type, Boolean)

Creates an instance of the specified type using that type's default constructor.

public static object CreateInstance (Type type, bool nonPublic);
Parameters
type
Type

The type of object to create.

nonPublic
Boolean

true if a public or nonpublic default constructor can match; false if only a public default constructor can match.

Returns

A reference to the newly created object.

Exceptions

type is null.

type is not a RuntimeType.

-or-

type is an open generic type (that is, the ContainsGenericParameters property returns true).

type cannot be a TypeBuilder.

-or-

Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or-

The assembly that contains type is a dynamic assembly that was created with Save.

The constructor being called throws an exception.

The caller does not have permission to call this constructor.

Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

No matching public constructor was found.

type is a COM object but the class identifier used to obtain the type is invalid, or the identified class is not registered.

type is not a valid type.

Remarks

Note

Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types and members if the caller has been granted ReflectionPermission with the System.Security.Permissions.ReflectionPermissionFlag flag and if the grant set of the assembly that contains the nonpublic types and members is restricted to the caller’s grant set or to a subset thereof. (See Security Considerations for Reflection.)

To use this functionality, your application should target the .NET Framework 3.5 or later.

CreateInstance(String, String)

Creates an instance of the type whose name is specified, using the named assembly and default constructor.

public static System.Runtime.Remoting.ObjectHandle CreateInstance (string assemblyName, string typeName);
Parameters
assemblyName
String

The name of the assembly where the type named typeName is sought. If assemblyName is null, the executing assembly is searched.

typeName
String

The fully qualified name of the preferred type.

Returns

A handle that must be unwrapped to access the newly created instance.

Exceptions

typeName is null.

No matching public constructor was found.

typename was not found in assemblyName.

assemblyName was not found.

The caller does not have permission to call this constructor.

You cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

The constructor, which was invoked through reflection, threw an exception.

The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

assemblyName is not a valid assembly.

-or-

The common language runtime (CLR) version 2.0 or later is currently loaded, and assemblyName was compiled for a version of the CLR that is later than the currently loaded version. Note that the .NET Framework versions 2.0, 3.0, and 3.5 all use CLR version 2.0.

An assembly or module was loaded twice with two different evidences.

-or-

The assembly name or code base is invalid.

Examples

The following example defines a class named Person in an assembly named PersonInfo. Note that the Person class has two constructors, one of which is parameterless.

using System;

public class Person
{
   private string _name;
   
   public Person()
   { }
   
   public Person(string name)
   {
      this._name = name;
   }
   
   public string Name
   { get { return this._name; }
     set { this._name = value; } }
   
   public override string ToString()
   {
      return this._name;
   }
}
Public Class Person
   Private _name As String
   
   Public Sub New()
   End Sub
   
   Public Sub New(name As String)
      Me._name = name
   End Sub
   
   Public Property Name As String
      Get
         Return Me._name
      End Get
      Set
         Me._name = value
      End Set
   End Property
   
   Public Overrides Function ToString() As String
      Return Me._name
   End Function
End Class

The following example calls the CreateInstance(String, String) method to instantiate the Person class. It requires a reference to PersonInfo.dll to be added to the project. Because the CreateInstance(String, String) method calls the Person class default constructor, the example assigns a value to its Name property.

using System;
using System.Runtime.Remoting;

public class Example
{
   public static void Main()
   {
      ObjectHandle handle = Activator.CreateInstance("PersonInfo", "Person");
      Person p = (Person) handle.Unwrap();
      p.Name = "Samuel";
      Console.WriteLine(p);
   }
}
// The example displays the following output:
//        Samuel
Imports System.Runtime.Remoting

Module Example
   Public Sub Main()
      Dim handle As ObjectHandle = Activator.CreateInstance("PersonInfo", "Person")
      Dim p As Person = CType(handle.Unwrap(), Person)
      p.Name = "Samuel"
      Console.WriteLine(p)
   End Sub
End Module
' The example displays the following output:
'       Samuel

However, CreateInstance is frequently called to instantiate a type that crosses machine boundaries or that is not known at design time. In this case, you cannot include a reference to the assembly in the project and cannot make early-bound calls to the type's members. To work around this limitation, the following example uses the CreateInstance method along with reflection to assign a value to the Person object's Name property and to display its value.

using System;
using System.Reflection;
using System.Runtime.Remoting;

public class Example
{
   public static void Main()
   {
      ObjectHandle handle = Activator.CreateInstance("PersonInfo", "Person");
      Object p = handle.Unwrap();
      Type t = p.GetType();
      PropertyInfo prop = t.GetProperty("Name");
      if (prop != null)
         prop.SetValue(p, "Samuel");

      MethodInfo method = t.GetMethod("ToString");
      Object retVal = method.Invoke(p, null); 
      if (retVal != null)
         Console.WriteLine(retVal);
   }
}
// The example displays the following output:
//        Samuel
Imports System.Reflection
Imports System.Runtime.Remoting

Module Example
   Public Sub Main()
      Dim handle As ObjectHandle = Activator.CreateInstance("PersonInfo", "Person")
      Dim p As Object = handle.Unwrap()
      Dim t As Type = p.GetType()
      Dim prop As PropertyInfo = t.GetProperty("Name")
      if Not prop Is Nothing Then
         prop.SetValue(p, "Samuel")
      End If   
      Dim method As MethodInfo = t.GetMethod("ToString")
      Dim retVal As Object = method.Invoke(p, Nothing) 
      If Not retVal Is Nothing Then
         Console.WriteLine(retVal)
      End If
   End Sub
End Module
' The example displays the following output:
'       Samuel

Remarks

Use System.Runtime.Remoting.ObjectHandle.Unwrap to unwrap the return value.

assemblyName can be either of the following:

  • The simple name of an assembly, without its path or file extension. For example, you would specify TypeExtensions for an assembly whose path and name are .\bin\TypeExtensions.dll.

  • The full name of a signed assembly, which consists of its simple name, version, culture, and public key token; for example, "TypeExtensions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=181869f2f7435b51".

For more information on how the common language runtime identifies and loads assemblies, see How the Runtime Locates Assemblies. For information on using the application configuration file to define assembly locations, see Specifying an Assembly's Location. If assemblyName is found, it is loaded in the default context.

Note

Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to create nonpublic types if the caller has been granted ReflectionPermission with the System.Security.Permissions.ReflectionPermissionFlag flag and if the grant set of the assembly that contains the nonpublic types is restricted to the caller’s grant set or to a subset thereof. (See Security Considerations for Reflection.)

To use this functionality, your application should target the .NET Framework 3.5 or later.

CreateInstance(ActivationContext, String[])

Creates an instance of the type that is designated by the specified ActivationContext object and activated with the specified custom activation data.

public static System.Runtime.Remoting.ObjectHandle CreateInstance (ActivationContext activationContext, string[] activationCustomData);
Parameters
activationContext
ActivationContext

An activation context object that specifies the object to create.

activationCustomData
System.String[]

An array of Unicode strings that contain custom activation data.

Returns

A handle that must be unwrapped to access the newly created object.

Remarks

Use the System.Runtime.Remoting.ObjectHandle.Unwrap method to unwrap the return value.

The activation context is used during manifest-based activation to set up the domain policy and to provide an application-based security model. The ActivationContext class contains an ApplicationIdentity object that provides access to the application manifest. For more information, see the ApplicationSecurityManager class.

CreateInstance(Type)

Creates an instance of the specified type using that type's default constructor.

public static object CreateInstance (Type type);
Parameters
type
Type

The type of object to create.

Returns

A reference to the newly created object.

Exceptions

type is null.

type is not a RuntimeType.

-or-

type is an open generic type (that is, the ContainsGenericParameters property returns true).

type cannot be a TypeBuilder.

-or-

Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

-or-

The assembly that contains type is a dynamic assembly that was created with Save.

The constructor being called throws an exception.

In the [.NET for Windows Store apps](http://go.microsoft.com/fwlink/?LinkID=247912) or the [Portable Class Library](~/docs/standard/cross-platform/cross-platform-development-with-the-portable-class-library.md), catch the base class exception, MemberAccessException, instead.

The caller does not have permission to call this constructor.

Cannot create an instance of an abstract class, or this member was invoked with a late-binding mechanism.

The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

In the [.NET for Windows Store apps](http://go.microsoft.com/fwlink/?LinkID=247912) or the [Portable Class Library](~/docs/standard/cross-platform/cross-platform-development-with-the-portable-class-library.md), catch the base class exception, MissingMemberException, instead.

No matching public constructor was found.

type is a COM object but the class identifier used to obtain the type is invalid, or the identified class is not registered.

type is not a valid type.

Examples

The following code example demonstrates how to call the CreateInstance(Type) method. Instances of several different types are created and their default values are displayed.

using namespace System;

ref class DynamicInstanceList
{
private:
    static String^ instanceSpec = "System.EventArgs;System.Random;" +
        "System.Exception;System.Object;System.Version";

public:
    static void Main()
    {
        array<String^>^ instances = instanceSpec->Split(';');
        Array^ instlist = Array::CreateInstance(Object::typeid, instances->Length);
        Object^ item;

        for (int i = 0; i < instances->Length; i++)
        {
            // create the object from the specification string
            Console::WriteLine("Creating instance of: {0}", instances[i]);
            item = Activator::CreateInstance(Type::GetType(instances[i]));
            instlist->SetValue(item, i);
        }
        Console::WriteLine("
Objects and their default values:
"); for each (Object^ o in instlist) { Console::WriteLine("Type: {0}
Value: {1}
HashCode: {2}
", o->GetType()->FullName, o->ToString(), o->GetHashCode()); } } }; int main() { DynamicInstanceList::Main(); } // This program will display output similar to the following: // // Creating instance of: System.EventArgs // Creating instance of: System.Random // Creating instance of: System.Exception // Creating instance of: System.Object // Creating instance of: System.Version // // Objects and their default values: // // Type: System.EventArgs // Value: System.EventArgs // HashCode: 46104728 // // Type: System.Random // Value: System.Random // HashCode: 12289376 // // Type: System.Exception // Value: System.Exception: Exception of type 'System.Exception' was thrown. // HashCode: 55530882 // // Type: System.Object // Value: System.Object // HashCode: 30015890 // // Type: System.Version // Value: 0.0 // HashCode: 1048575
using System;

class DynamicInstanceList
{
    private static string instanceSpec = "System.EventArgs;System.Random;" +
        "System.Exception;System.Object;System.Version";

    public static void Main()
    {
        string[] instances = instanceSpec.Split(';');
        Array instlist = Array.CreateInstance(typeof(object), instances.Length);
        object item;
        for (int i = 0; i < instances.Length; i++)
        {
            // create the object from the specification string
            Console.WriteLine("Creating instance of: {0}", instances[i]);
            item = Activator.CreateInstance(Type.GetType(instances[i]));
            instlist.SetValue(item, i);
        }
        Console.WriteLine("
Objects and their default values:
"); foreach (object o in instlist) { Console.WriteLine("Type: {0}
Value: {1}
HashCode: {2}
", o.GetType().FullName, o.ToString(), o.GetHashCode()); } } } // This program will display output similar to the following: // // Creating instance of: System.EventArgs // Creating instance of: System.Random // Creating instance of: System.Exception // Creating instance of: System.Object // Creating instance of: System.Version // // Objects and their default values: // // Type: System.EventArgs // Value: System.EventArgs // HashCode: 46104728 // // Type: System.Random // Value: System.Random // HashCode: 12289376 // // Type: System.Exception // Value: System.Exception: Exception of type 'System.Exception' was thrown. // HashCode: 55530882 // // Type: System.Object // Value: System.Object // HashCode: 30015890 // // Type: System.Version // Value: 0.0 // HashCode: 1048575
Imports System

Class DynamicInstanceList
    Private Shared instanceSpec As String = "System.EventArgs;System.Random;" + _
        "System.Exception;System.Object;System.Version"

    Public Shared Sub Main()
        Dim instances() As String = instanceSpec.Split(";")
        Dim instlist As Array = Array.CreateInstance(GetType(Object), instances.Length)
        Dim item As Object

        For i As Integer = 0 To instances.Length -1
            ' create the object from the specification string
            Console.WriteLine("Creating instance of: {0}", instances(i))
            item = Activator.CreateInstance(Type.GetType(instances(i)))
            instlist.SetValue(item, i)
        Next i
        Console.WriteLine(vbNewLine + "Objects and their default values:" + vbNewLine)
        For Each o As Object In instlist
            Console.WriteLine("Type:     {0}" + vbNewLine + "Value:    {1}" + _
                vbNewLine + "HashCode: {2}" + vbNewLine, _
                o.GetType().FullName, o.ToString(), o.GetHashCode())
        Next o
    End Sub
End Class

' This program will display output similar to the following:
'
' Creating instance of: System.EventArgs
' Creating instance of: System.Random
' Creating instance of: System.Exception
' Creating instance of: System.Object
' Creating instance of: System.Version
'
' Objects and their default values:
'
' Type:     System.EventArgs
' Value:    System.EventArgs
' HashCode: 46104728
'
' Type:     System.Random
' Value:    System.Random
' HashCode: 12289376
'
' Type:     System.Exception
' Value:    System.Exception: Exception of type 'System.Exception' was thrown.
' HashCode: 55530882
'
' Type:     System.Object
' Value:    System.Object
' HashCode: 30015890
'
' Type:     System.Version
' Value:    0.0
' HashCode: 1048575

Remarks

The constructor to be invoked must be accessible.

Note

Starting with the .NET Framework 2.0 Service Pack 1, this method can be used to access nonpublic types if the caller has been granted ReflectionPermission with the System.Security.Permissions.ReflectionPermissionFlag flag and if the grant set of the assembly that contains the nonpublic types is restricted to the caller’s grant set or to a subset thereof. (See Security Considerations for Reflection.)

To use this functionality, your application should target the .NET Framework 3.5 or later.

CreateInstance(ActivationContext)

Creates an instance of the type designated by the specified ActivationContext object.

public static System.Runtime.Remoting.ObjectHandle CreateInstance (ActivationContext activationContext);
Parameters
activationContext
ActivationContext

An activation context object that specifies the object to create.

Returns

A handle that must be unwrapped to access the newly created object.

Remarks

Use the System.Runtime.Remoting.ObjectHandle.Unwrap method to unwrap the return value.

The activation context is used during manifest-based activation to set up the domain policy and to provide an application-based security model. The ActivationContext class contains an ApplicationIdentity object that provides access to the application manifest. For more information, see the ApplicationSecurityManager class.

CreateInstance(AppDomain, String, String)

Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and default constructor.

[System.Security.SecurityCritical]
public static System.Runtime.Remoting.ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName);
Parameters
domain
AppDomain

The remote domain where the type named typeName is created.

assemblyName
String

The name of the assembly where the type named typeName is sought. If assemblyName is null, the executing assembly is searched.

typeName
String

The fully qualified name of the preferred type.

Returns

A handle that must be unwrapped to access the newly created instance.

Attributes
Exceptions

typeName or domain is null.

No matching public constructor was found.

typename was not found in assemblyName.

assemblyName was not found.

The caller does not have permission to call this constructor.

Cannot create an instance of an abstract type.

-or-

This member was invoked with a late-binding mechanism.

The constructor, which was invoked through reflection, threw an exception.

The COM type was not obtained through GetTypeFromProgID or GetTypeFromCLSID.

Creation of TypedReference, ArgIterator, Void, and RuntimeArgumentHandle types, or arrays of those types, is not supported.

assemblyName is not a valid assembly.

-or-

The common language runtime (CLR) version 2.0 or later is currently loaded, and assemblyName was compiled for a version of the CLR that is later than the currently loaded version. Note that the .NET Framework versions 2.0, 3.0, and 3.5 all use CLR version 2.0.

An assembly or module was loaded twice with two different evidences.

-or-

The assembly name or code base is invalid.

Remarks

Use CreateInstance when a host needs to execute code in an application domain that has restricted security permissions.

Use System.Runtime.Remoting.ObjectHandle.Unwrap to unwrap the return value.

Note

This method uses System.Security.Permissions.SecurityAction to require the immediate caller to have full trust.

CreateInstance<T>()

Creates an instance of the type designated by the specified generic type parameter, using the parameterless constructor.

public static T CreateInstance<T> ();
Type Parameters
T

The type to create.

Returns
T

A reference to the newly created object.

Exceptions

In the [.NET for Windows Store apps](http://go.microsoft.com/fwlink/?LinkID=247912) or the [Portable Class Library](~/docs/standard/cross-platform/cross-platform-development-with-the-portable-class-library.md), catch the base class exception, MissingMemberException, instead.

The type that is specified for T does not have a parameterless constructor.

Remarks

The CreateInstance<T>() generic method is used by compilers to implement the instantiation of types specified by type parameters. For example, in the following generic method, the implementation of new T() (gcnew T() in C++) uses the CreateInstance<T>() generic method.

public:
    generic <typename T> where T:gcnew()
    static T Bar()
    {
        return gcnew T();
    }
public static T Factory<T>() where T:new()
{
    return new T();
}
Public Shared Function Factory(Of T As New)() As T
    Return New T()
End Function

In general, there is no use for the CreateInstance<T>() generic method in application code, because the type must be known at compile time. If the type is known at compile time, normal instantiation syntax can be used (new operator in C#, New in Visual Basic, gcnew in C++). If the type is not known at compile time, you can call a non-generic overload of CreateInstance.

There are no overloads of the CreateInstance<T>() generic method that take argument lists, because the non-generic overloads of CreateInstance already provide late-bound constructor resolution.