Επεξεργασία

Κοινή χρήση μέσω


Activator.CreateInstance Method

Definition

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

Overloads

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

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.

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.

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.

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

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

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

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

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

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

CreateInstance(String, String, Object[])

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

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

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

CreateInstance(Type, Object[])

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

CreateInstance(Type, Boolean)

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

CreateInstance(String, String)

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

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.

CreateInstance(Type)

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

CreateInstance(ActivationContext)

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

CreateInstance(AppDomain, String, String)

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

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

Caution

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.

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.

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(AppDomain ^ domain, System::String ^ assemblyName, System::String ^ typeName, bool ignoreCase, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture, cli::array <System::Object ^> ^ activationAttributes, System::Security::Policy::Evidence ^ securityAttributes);
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);
[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);
static member CreateInstance : AppDomain * string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] * System.Security.Policy.Evidence -> System.Runtime.Remoting.ObjectHandle
[<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>]
static member CreateInstance : AppDomain * string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] * System.Security.Policy.Evidence -> System.Runtime.Remoting.ObjectHandle
Public Shared Function CreateInstance (domain As AppDomain, assemblyName As String, typeName As String, ignoreCase As Boolean, bindingAttr As BindingFlags, binder As Binder, args As Object(), culture As CultureInfo, activationAttributes As Object(), securityAttributes As Evidence) As ObjectHandle

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 type to create an instance of.

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
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 parameterless 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
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 object, or null for Nullable<T> instances with no value.

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 ObjectHandle.Unwrap to unwrap the return value.

Applies to

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.

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(AppDomain ^ domain, System::String ^ assemblyName, System::String ^ typeName, bool ignoreCase, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture, cli::array <System::Object ^> ^ activationAttributes);
[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.SecurityCritical>]
static member CreateInstance : AppDomain * string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] -> System.Runtime.Remoting.ObjectHandle
Public Shared Function CreateInstance (domain As AppDomain, assemblyName As String, typeName As String, ignoreCase As Boolean, bindingAttr As BindingFlags, binder As Binder, args As Object(), culture As CultureInfo, activationAttributes As Object()) As ObjectHandle

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 type to create an instance of.

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
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 parameterless 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
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 object, or null for Nullable<T> instances with no value.

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 ObjectHandle.Unwrap to unwrap the return value.

Applies to

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

Source:
Activator.RuntimeType.cs
Source:
Activator.RuntimeType.cs
Source:
Activator.RuntimeType.cs

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(System::String ^ assemblyName, System::String ^ typeName, bool ignoreCase, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture, cli::array <System::Object ^> ^ activationAttributes);
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);
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);
static member CreateInstance : string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] -> System.Runtime.Remoting.ObjectHandle
Public Shared Function CreateInstance (assemblyName As String, typeName As String, ignoreCase As Boolean, bindingAttr As BindingFlags, binder As Binder, args As Object(), culture As CultureInfo, activationAttributes As Object()) As ObjectHandle

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 type to create an instance of.

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
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 parameterless 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
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, or null for Nullable<T> instances with no value.

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 ObjectHandle.Unwrap to unwrap the return value.

Note

Starting with .NET Framework 2.0, this method can be used to create nonpublic types and members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess 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 .NET Framework 3.5 or later.

Applies to

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

Source:
Activator.RuntimeType.cs
Source:
Activator.RuntimeType.cs
Source:
Activator.RuntimeType.cs

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

public:
 static System::Object ^ CreateInstance(Type ^ type, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture, cli::array <System::Object ^> ^ activationAttributes);
public static object? CreateInstance (Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture, object?[]? activationAttributes);
public static object CreateInstance (Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes);
static member CreateInstance : Type * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] -> obj
Public Shared Function CreateInstance (type As Type, bindingAttr As BindingFlags, binder As Binder, args As Object(), culture As CultureInfo, activationAttributes As Object()) As Object

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
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 parameterless 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
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, or null for Nullable<T> instances with no value.

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 .NET Framework 2.0, this method can be used to access nonpublic types and members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess 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 .NET Framework 3.5 or later.

Applies to

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

Source:
Activator.cs
Source:
Activator.cs
Source:
Activator.cs

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

public:
 static System::Object ^ CreateInstance(Type ^ type, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture);
public static object? CreateInstance (Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder? binder, object?[]? args, System.Globalization.CultureInfo? culture);
public static object CreateInstance (Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture);
static member CreateInstance : Type * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo -> obj
Public Shared Function CreateInstance (type As Type, bindingAttr As BindingFlags, binder As Binder, args As Object(), culture As CultureInfo) As Object

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
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 parameterless 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, or null for Nullable<T> instances with no value.

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 .NET Framework 2.0, this method can be used to access nonpublic types and members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess 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 .NET Framework 3.5 or later.

Applies to

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

Source:
Activator.cs
Source:
Activator.cs
Source:
Activator.cs

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

public:
 static System::Object ^ CreateInstance(Type ^ type, cli::array <System::Object ^> ^ args, cli::array <System::Object ^> ^ activationAttributes);
public static object? CreateInstance (Type type, object?[]? args, object?[]? activationAttributes);
public static object CreateInstance (Type type, object[] args, object[] activationAttributes);
static member CreateInstance : Type * obj[] * obj[] -> obj
Public Shared Function CreateInstance (type As Type, args As Object(), activationAttributes As Object()) As Object

Parameters

type
Type

The type of object to create.

args
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 parameterless constructor) is invoked.

activationAttributes
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, or null for Nullable<T> instances with no value.

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 .NET Framework 2.0, this method can be used to access nonpublic types if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess 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 .NET Framework 3.5 or later.

Applies to

CreateInstance(String, String, Object[])

Source:
Activator.RuntimeType.cs
Source:
Activator.RuntimeType.cs
Source:
Activator.RuntimeType.cs

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

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(System::String ^ assemblyName, System::String ^ typeName, cli::array <System::Object ^> ^ activationAttributes);
public static System.Runtime.Remoting.ObjectHandle? CreateInstance (string assemblyName, string typeName, object?[]? activationAttributes);
public static System.Runtime.Remoting.ObjectHandle CreateInstance (string assemblyName, string typeName, object[] activationAttributes);
static member CreateInstance : string * string * obj[] -> System.Runtime.Remoting.ObjectHandle
Public Shared Function CreateInstance (assemblyName As String, typeName As String, activationAttributes As Object()) As ObjectHandle

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 type to create an instance of.

activationAttributes
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 object, or null for Nullable<T> instances.

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.

The invoked constructor throws an exception.

-or-

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

Remarks

Use ObjectHandle.Unwrap to unwrap the return value.

Note

Starting with .NET Framework 2.0, this method can be used to create nonpublic types if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess 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 .NET Framework 3.5 or later.

Applies to

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

Caution

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.

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(System::String ^ assemblyName, System::String ^ typeName, bool ignoreCase, System::Reflection::BindingFlags bindingAttr, System::Reflection::Binder ^ binder, cli::array <System::Object ^> ^ args, System::Globalization::CultureInfo ^ culture, cli::array <System::Object ^> ^ activationAttributes, System::Security::Policy::Evidence ^ securityInfo);
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);
[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);
static member CreateInstance : string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] * System.Security.Policy.Evidence -> System.Runtime.Remoting.ObjectHandle
[<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.")>]
static member CreateInstance : string * string * bool * System.Reflection.BindingFlags * System.Reflection.Binder * obj[] * System.Globalization.CultureInfo * obj[] * System.Security.Policy.Evidence -> System.Runtime.Remoting.ObjectHandle
Public Shared Function CreateInstance (assemblyName As String, typeName As String, ignoreCase As Boolean, bindingAttr As BindingFlags, binder As Binder, args As Object(), culture As CultureInfo, activationAttributes As Object(), securityInfo As Evidence) As ObjectHandle

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 type to create an instance of.

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
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 parameterless 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
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 object, or null for Nullable<T> instances with no value.

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 ObjectHandle.Unwrap to unwrap the return value.

Note

Starting with .NET Framework 2.0, this method can be used to create nonpublic types and members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess 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 .NET Framework 3.5 or later.

Applies to

CreateInstance(Type, Object[])

Source:
Activator.cs
Source:
Activator.cs
Source:
Activator.cs

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

public:
 static System::Object ^ CreateInstance(Type ^ type, ... cli::array <System::Object ^> ^ args);
public:
 static System::Object ^ CreateInstance(Type ^ type, cli::array <System::Object ^> ^ args);
public static object CreateInstance (Type type, params object[] args);
public static object? CreateInstance (Type type, params object?[]? args);
public static object CreateInstance (Type type, object[] args);
static member CreateInstance : Type * obj[] -> obj
Public Shared Function CreateInstance (type As Type, ParamArray args As Object()) As Object
Public Shared Function CreateInstance (type As Type, args As Object()) As Object

Parameters

type
Type

The type of object to create.

args
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 parameterless constructor) is invoked.

Returns

A reference to the newly created object, or null for Nullable<T> instances with no value.

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.

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

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.

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

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 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
open System

// Initialize array of characters from a to z.
let chars = [| 'a' .. 'z' |]

let obj = Activator.CreateInstance(typeof<string>, chars[13..22])

printfn $"{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
open System

let chars = [| 'a' .. 'f' |]

let arguments =
    [| chars
       chars[1..4]
       Array.create 20 chars[1] |]

for args in arguments do
    let result =
        Activator.CreateInstance(typeof<string>, args)

    printfn $"{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 .NET Framework 2.0, this method can be used to access nonpublic types if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess 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 .NET Framework 3.5 or later.

Applies to

CreateInstance(Type, Boolean)

Source:
Activator.RuntimeType.cs
Source:
Activator.RuntimeType.cs
Source:
Activator.RuntimeType.cs

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

public:
 static System::Object ^ CreateInstance(Type ^ type, bool nonPublic);
public static object? CreateInstance (Type type, bool nonPublic);
public static object CreateInstance (Type type, bool nonPublic);
static member CreateInstance : Type * bool -> obj
Public Shared Function CreateInstance (type As Type, nonPublic As Boolean) As Object

Parameters

type
Type

The type of object to create.

nonPublic
Boolean

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

Returns

A reference to the newly created object, or null for Nullable<T> instances.

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 .NET Framework 2.0, this method can be used to access nonpublic types and members if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess 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 .NET Framework 3.5 or later.

Applies to

CreateInstance(String, String)

Source:
Activator.RuntimeType.cs
Source:
Activator.RuntimeType.cs
Source:
Activator.RuntimeType.cs

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

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(System::String ^ assemblyName, System::String ^ typeName);
public static System.Runtime.Remoting.ObjectHandle? CreateInstance (string assemblyName, string typeName);
public static System.Runtime.Remoting.ObjectHandle CreateInstance (string assemblyName, string typeName);
static member CreateInstance : string * string -> System.Runtime.Remoting.ObjectHandle
Public Shared Function CreateInstance (assemblyName As String, typeName As String) As ObjectHandle

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 type to create an instance of.

Returns

A handle that must be unwrapped to access the newly created object, or null for Nullable<T> instances.

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;
   }
}
type Person(name) =
    member val Name = name with get, set

    override this.ToString() = this.Name

    new () = Person Unchecked.defaultof<string>
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 parameterless 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
open System

let handle = Activator.CreateInstance("PersonInfo", "Person")
let p = handle.Unwrap() :?> Person
p.Name <- "Samuel"
printfn $"{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
open System

let handle =
    Activator.CreateInstance("PersonInfo", "Person")

let p = handle.Unwrap()
let t = p.GetType()
let prop = t.GetProperty "Name"

if not (isNull prop) then
    prop.SetValue(p, "Samuel")

let method = t.GetMethod "ToString"
let retVal = method.Invoke(p, null)

if not (isNull retVal) then
    printfn $"{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 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 .NET Framework 2.0, this method can be used to create nonpublic types if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess 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 .NET Framework 3.5 or later.

Applies to

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, cli::array <System::String ^> ^ activationCustomData);
public static System.Runtime.Remoting.ObjectHandle CreateInstance (ActivationContext activationContext, string[] activationCustomData);
static member CreateInstance : ActivationContext * string[] -> System.Runtime.Remoting.ObjectHandle
Public Shared Function CreateInstance (activationContext As ActivationContext, activationCustomData As String()) As ObjectHandle

Parameters

activationContext
ActivationContext

An activation context object that specifies the object to create.

activationCustomData
String[]

An array of Unicode strings that contain custom activation data.

Returns

A handle that must be unwrapped to access the newly created object, or null for Nullable<T> instances.

Remarks

Use the 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.

See also

Applies to

CreateInstance(Type)

Source:
Activator.cs
Source:
Activator.cs
Source:
Activator.cs

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

public:
 static System::Object ^ CreateInstance(Type ^ type);
public static object CreateInstance (Type type);
public static object? CreateInstance (Type type);
static member CreateInstance : Type -> obj
Public Shared Function CreateInstance (type As Type) As Object

Parameters

type
Type

The type of object to create.

Returns

A reference to the newly created object, or null for Nullable<T> instances.

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.

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

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.

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

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("\nObjects and their default values:\n");
        for each (Object^ o in instlist)
        {
            Console::WriteLine("Type:     {0}\nValue:    {1}\nHashCode: {2}\n",
                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("\nObjects and their default values:\n");
        foreach (object o in instlist)
        {
            Console.WriteLine("Type:     {0}\nValue:    {1}\nHashCode: {2}\n",
                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
open System

let instanceSpec =
    "System.EventArgs;System.Random;System.Exception;System.Object;System.Version"

let instances = instanceSpec.Split ';'
let instlist = Array.zeroCreate instances.Length
let mutable item = obj ()

for i = 0 to instances.Length - 1 do
    // create the object from the specification string
    printfn $"Creating instance of: {instances.[i]}"
    item <- Activator.CreateInstance(Type.GetType instances.[i])
    instlist.[i] <- item

printfn "\nObjects and their default values:\n"

for o in instlist do
    printfn $"Type:     {o.GetType().FullName}\nValue:    {o}\nHashCode: {o.GetHashCode()}\n"


// 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
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(Environment.NewLine + "Objects and their default values:" + Environment.NewLine)
        For Each o As Object In instlist
            Console.WriteLine("Type:     {0}" + Environment.NewLine + "Value:    {1}" + _
                Environment.NewLine + "HashCode: {2}" + Environment.NewLine, _
                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 .NET Framework 2.0, this method can be used to access nonpublic types if the caller has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess 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 .NET Framework 3.5 or later.

Applies to

CreateInstance(ActivationContext)

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

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(ActivationContext ^ activationContext);
public static System.Runtime.Remoting.ObjectHandle CreateInstance (ActivationContext activationContext);
static member CreateInstance : ActivationContext -> System.Runtime.Remoting.ObjectHandle
Public Shared Function CreateInstance (activationContext As ActivationContext) As ObjectHandle

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, or null for Nullable<T> instances.

Remarks

Use the 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.

See also

Applies to

CreateInstance(AppDomain, String, String)

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

public:
 static System::Runtime::Remoting::ObjectHandle ^ CreateInstance(AppDomain ^ domain, System::String ^ assemblyName, System::String ^ typeName);
public static System.Runtime.Remoting.ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName);
[System.Security.SecurityCritical]
public static System.Runtime.Remoting.ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName);
static member CreateInstance : AppDomain * string * string -> System.Runtime.Remoting.ObjectHandle
[<System.Security.SecurityCritical>]
static member CreateInstance : AppDomain * string * string -> System.Runtime.Remoting.ObjectHandle
Public Shared Function CreateInstance (domain As AppDomain, assemblyName As String, typeName As String) As ObjectHandle

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 type to create an instance of.

Returns

A handle that must be unwrapped to access the newly created object, or null for Nullable<T> instances.

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 ObjectHandle.Unwrap to unwrap the return value.

Applies to

CreateInstance<T>()

Source:
Activator.RuntimeType.cs
Source:
Activator.RuntimeType.cs
Source:
Activator.RuntimeType.cs

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

public:
generic <typename T>
 static T CreateInstance();
public static T CreateInstance<T> ();
static member CreateInstance : unit -> 'T
Public Shared Function CreateInstance(Of T) () As T

Type Parameters

T

The type to create.

Returns

T

A reference to the newly created object, or null for Nullable<T> instances.

Exceptions

Cannot create an instance of an abstract class, or the type that is specified for T does not have a parameterless constructor.

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

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();
}
let factory<'T when 'T : (new: unit -> 'T)> =
    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.

Applies to