KGy SOFT

CreateInstanceAccessor Class

KGy SOFT Core Libraries Help
Provides an efficient way for creating objects via dynamically created delegates.
See the Remarks section for details and an example.
Inheritance Hierarchy

SystemObject
  KGySoft.ReflectionMemberAccessor
    KGySoft.ReflectionCreateInstanceAccessor

Namespace:  KGySoft.Reflection
Assembly:  KGySoft.CoreLibraries (in KGySoft.CoreLibraries.dll) Version: 5.0.0-rc.1
Syntax

public abstract class CreateInstanceAccessor : MemberAccessor

The CreateInstanceAccessor type exposes the following members.

Properties

  NameDescription
Public propertyMemberInfo
Gets the reflection member info of the accessed member.
(Inherited from MemberAccessor.)
Top
Methods

  NameDescription
Public methodCreateInstance
Creates a new instance by the associated ConstructorInfo or Type. For types and parameterless constructors the parameters parameter is omitted.
Public methodEquals
Determines whether the specified Object is equal to the current MemberAccessor.
(Inherited from MemberAccessor.)
Protected methodFinalize
Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
(Inherited from Object.)
Public methodStatic memberGetAccessor(ConstructorInfo)
Gets a CreateInstanceAccessor for the specified ConstructorInfo.
Public methodStatic memberGetAccessor(Type)
Gets a CreateInstanceAccessor for the specified Type. Given type must have a parameterless constructor or type must be ValueType.
Public methodGetHashCode
Gets a hash code for the current MemberAccessor instance.
(Inherited from MemberAccessor.)
Public methodGetType
Gets the Type of the current instance.
(Inherited from Object.)
Protected methodMemberwiseClone
Creates a shallow copy of the current Object.
(Inherited from Object.)
Public methodToString
Returns a String that represents the current MemberAccessor.
(Inherited from MemberAccessor.)
Top
Extension Methods

  NameDescription
Public Extension MethodConvert(Type, CultureInfo)Overloaded.
Converts an Object specified in the obj parameter to the desired targetType.
See the Examples section of the generic ConvertTTarget(Object, CultureInfo) overload for an example.
(Defined by ObjectExtensions.)
Public Extension MethodCode exampleConvertTTarget(CultureInfo)Overloaded.
Converts an Object specified in the obj parameter to the desired TTarget.
(Defined by ObjectExtensions.)
Public Extension MethodIn (Defined by ObjectExtensions.)
Public Extension MethodTryConvert(Type, Object)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired targetType.
(Defined by ObjectExtensions.)
Public Extension MethodTryConvert(Type, CultureInfo, Object)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired targetType.
(Defined by ObjectExtensions.)
Public Extension MethodTryConvertTTarget(TTarget)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired TTarget.
See the Examples section of the ConvertTTarget(Object, CultureInfo) method for a related example.
(Defined by ObjectExtensions.)
Public Extension MethodTryConvertTTarget(CultureInfo, TTarget)Overloaded.
Tries to convert an Object specified in the obj parameter to the desired TTarget.
See the Examples section of the ConvertTTarget(Object, CultureInfo) method for a related example.
(Defined by ObjectExtensions.)
Top
Remarks

You can obtain a CreateInstanceAccessor instance by the static GetAccessor methods. There are two overloads of them: GetAccessor(Type) can be used for types with parameterless constructors and for creating value types without a constructor, and the GetAccessor(ConstructorInfo) overload is for creating an instance by a specified constructor (with or without parameters).

The CreateInstance method can be used to create an actual instance of an object. The first call of this method is slow because the delegate is generated on the first access, but further calls are much faster.

The already obtained accessors are cached so subsequent GetAccessor calls return the already created accessors unless they were dropped out from the cache, which can store about 8000 elements.

Note Note
If you want to create an instance just by enlisting the constructor parameters of a Type rather than specifying a ConstructorInfo, then you can use the CreateInstance methods in the Reflector class, which have some overloads for that purpose.
Caution note Caution
The .NET Standard 2.0 version of the CreateInstance does not return the ref/out parameters.
If you reference the .NET Standard 2.0 version of the KGySoft.CoreLibraries assembly, then use the Reflector.CreateInstance methods to invoke constructors with ref/out parameters without losing the returned parameter values.
Examples

C#
using System;
using System.Reflection;
using KGySoft.Diagnostics;
using KGySoft.Reflection;

class Example
{
    private class TestClass
    {
        public TestClass() { }
        public TestClass(int i) { }
    }

    static void Main(string[] args)
    {
        Type testType = typeof(TestClass);
        ConstructorInfo ctorDefault = testType.GetConstructor(Type.EmptyTypes);
        ConstructorInfo ctorWithParameters = testType.GetConstructor(new[] { typeof(int) });
        CreateInstanceAccessor accessorForType = CreateInstanceAccessor.GetAccessor(testType);
        CreateInstanceAccessor accessorForCtor = CreateInstanceAccessor.GetAccessor(ctorWithParameters);

        new PerformanceTest { Iterations = 1000000 }
            .AddCase(() => new TestClass(), "Default constructor direct call")
            .AddCase(() => new TestClass(1), "Parameterized constructor direct call")
            .AddCase(() => Activator.CreateInstance(testType), "Activator.CreateInstance by type")
            .AddCase(() => Activator.CreateInstance(testType, 1), "Activator.CreateInstance by constructor parameters")
            .AddCase(() => ctorDefault.Invoke(null), "ConstructorInfo.Invoke (default constructor)")
            .AddCase(() => ctorWithParameters.Invoke(new object[] { 1 }), "ConstructorInfo.Invoke (parameterized constructor)")
            .AddCase(() => accessorForType.CreateInstance(), "CreateInstanceAccessor.CreateInstance (for type)")
            .AddCase(() => accessorForCtor.CreateInstance(1), "CreateInstanceAccessor.CreateInstance (parameterized constructor)")
            .DoTest()
            .DumpResults(Console.Out);
    }
}

// This code example produces a similar output to this one:
// ==[Performance Test Results]================================================
// Iterations: 1,000,000
// Warming up: Yes
// Test cases: 8
// Calling GC.Collect: Yes
// Forced CPU Affinity: 2
// Cases are sorted by time (quickest first)
// --------------------------------------------------
// 1. Default constructor direct call: average time: 4.27 ms
// 2. Parameterized constructor direct call: average time: 4.99 ms (+0.72 ms / 116.89 %)
// 3. CreateInstanceAccessor.CreateInstance (for type): average time: 25.57 ms (+21.30 ms / 599.00 %)
// 4. CreateInstanceAccessor.CreateInstance (parameterized constructor): average time: 26.57 ms (+22.30 ms / 622.28 %)
// 5. Activator.CreateInstance by type: average time: 57.60 ms (+53.33 ms / 1,349.24 %)
// 6. ConstructorInfo.Invoke (default constructor): average time: 163.87 ms (+159.60 ms / 3,838.56 %)
// 7. ConstructorInfo.Invoke (parameterized constructor): average time: 225.14 ms (+220.87 ms / 5,273.79 %)
// 8. Activator.CreateInstance by constructor parameters: average time: 689.54 ms (+685.27 ms / 16,152.22 %)
See Also

Reference