CreateInstanceAccessorCreateInstance(Object) Method

Creates a new instance by the associated ConstructorInfo or Type. For types and parameterless constructors the parameters parameter is omitted.

Definition

Namespace: KGySoft.Reflection
Assembly: KGySoft.CoreLibraries (in KGySoft.CoreLibraries.dll) Version: 10.0.0
C#
public Object CreateInstance(
	params Object?[]? parameters
)

Parameters

parameters  Object
The parameters for parameterized constructors.

Return Value

Object
The created instance.

Remarks

Invoking the constructor for the first time is slower than the System.Reflection.MethodBase.Invoke method but further calls are much faster.

If the constructor has ref/ parameters pass a preallocated array to parameters. The parameters passed by reference will be assigned back to the corresponding array elements.

  Tip

If the constructor has no more than four parameters, then you can use the generic CreateInstance overloads for better performance if the types are known at compile time.

  Notes to Callers

If the constructor has ref/ or pointer parameters, then the .NET Standard 2.0 version of this method defaults to use regular reflection to be able to assign the parameter values back to the parameters array. To experience the best performance try to target .NET Standard 2.1 or any .NET Framework or .NET Core/.NET platforms instead.

Exceptions

ArgumentNullExceptionThis CreateInstanceAccessor represents a constructor with parameters and parameters is .
ArgumentExceptionThe type of one of the parameters is invalid.
-or-
parameters has too few elements.
InvalidOperationExceptionThis CreateInstanceAccessor represents a static constructor, a constructor of an abstract class, or.a constructor of an open generic type.
NotSupportedExceptionOn .NET Framework the code is executed in a partially trusted domain with insufficient permissions.

See Also