KGy SOFT

FieldAccessor Class

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

SystemObject
  KGySoft.ReflectionMemberAccessor
    KGySoft.ReflectionFieldAccessor

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

public sealed class FieldAccessor : MemberAccessor

The FieldAccessor type exposes the following members.

Properties

  NameDescription
Public propertyIsConstant
Gets whether the field is a constant. Constant fields cannot be set.
Public propertyIsReadOnly
Gets whether the field is read-only.
Public propertyMemberInfo
Gets the reflection member info of the accessed member.
(Inherited from MemberAccessor.)
Top
Methods

  NameDescription
Public methodEquals
Determines whether the specified Object is equal to the current MemberAccessor.
(Inherited from MemberAccessor.)
Public methodGet
Gets the value of the field. For static fields the instance parameter is omitted (can be ).
Public methodStatic memberGetAccessor
Gets a FieldAccessor for the specified field.
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.)
Public methodSet
Sets the field. For static fields the instance parameter is omitted (can be ).
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 FieldAccessor instance by the static GetAccessor method.

The Get and Set methods can be used to get and set the field, respectively. The first call of these methods are slow because the delegates are 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 access a property by name rather then by a FieldInfo, then you can use the SetField and GetField methods in the Reflector class, which have some overloads with a fieldName parameter.
Caution note Caution
The .NET Standard 2.0 version of the Set method throws a PlatformNotSupportedException if the field to set is read-only or is an instance member of a value type (struct).
If you reference the .NET Standard 2.0 version of the KGySoft.CoreLibraries assembly, then use the Reflector.SetField methods to set read-only or value type instance fields.
Examples

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

class Example
{
    private class TestClass
    {
        public int TestField;
    }

    static void Main(string[] args)
    {
        var instance = new TestClass();
        FieldInfo field = instance.GetType().GetField(nameof(TestClass.TestField));
        FieldAccessor accessor = FieldAccessor.GetAccessor(field);

        new PerformanceTest { TestName = "Set Field", Iterations = 1000000 }
            .AddCase(() => instance.TestField = 1, "Direct set")
            .AddCase(() => field.SetValue(instance, 1), "FieldInfo.SetValue")
            .AddCase(() => accessor.Set(instance, 1), "FieldAccessor.Set")
            .DoTest()
            .DumpResults(Console.Out);

        new PerformanceTest<int> { TestName = "Get Field", Iterations = 1000000 }
            .AddCase(() => instance.TestField, "Direct get")
            .AddCase(() => (int)field.GetValue(instance), "FieldInfo.GetValue")
            .AddCase(() => (int)accessor.Get(instance), "FieldAccessor.Get")
            .DoTest()
            .DumpResults(Console.Out);
    }
}

// This code example produces a similar output to this one:
// ==[Set Field Results]================================================
// Iterations: 1,000,000
// Warming up: Yes
// Test cases: 3
// Calling GC.Collect: Yes
// Forced CPU Affinity: 2
// Cases are sorted by time (quickest first)
// --------------------------------------------------
// 1. Direct set: average time: 2.58 ms
// 2. FieldAccessor.Set: average time: 10.92 ms (+8.34 ms / 422.84 %)
// 3. FieldInfo.SetValue: average time: 110.98 ms (+108.40 ms / 4,296.20 %)
// 
// ==[Get Field Results]================================================
// Iterations: 1,000,000
// Warming up: Yes
// Test cases: 3
// Calling GC.Collect: Yes
// Forced CPU Affinity: 2
// Cases are sorted by time (quickest first)
// --------------------------------------------------
// 1. Direct get: average time: 2.99 ms
// 2. FieldAccessor.Get: average time: 8.56 ms (+5.58 ms / 286.69 %)
// 3. FieldInfo.GetValue: average time: 111.37 ms (+108.38 ms / 3,729.24 %)
See Also

Reference