Sets a private field given by it's name on a specific object. - CSharp System.Reflection

CSharp examples for System.Reflection:FieldInfo

Description

Sets a private field given by it's name on a specific object.

Demo Code

// The MIT License (MIT)
using System.Reflection;
using System;/*w  ww  .  ja  va 2 s . co  m*/

public class Main{
        /// <summary>
        /// Sets a private field given by it's name on a specific object.
        /// </summary>
        /// <param name="target">The target object on which to set the field.</param>
        /// <param name="name">The name of the field to set.</param>
        /// <param name="value">The value to assign to the field.</param>
        /// <example>
        /// public void AsExtentionMethod()
        /// {
        ///   MyClass myObjectOfMyClass = new MyClass();
        ///   myObjectOfMyClass.SetPrivateField("myField", "MyValue");
        /// }
        /// 
        /// public void AsStaticMethod()
        /// {
        ///   MyClass myObjectOfMyClass = new MyClass();
        ///   PrivateMembersHelper.SetPrivateField(myObjectOfMyClass, "myField", "MyValue");
        /// }
        /// </example>
        public static void SetPrivateField(this object target, string name, object value)
        {
            FieldInfo field = target.GetType().LocateField(name);
            field.SetValue(target, value);
        }
        private static FieldInfo LocateField(this Type targetType, string name)
        {
            try
            {
                FieldInfo fieldInfo = targetType.GetField(name, ALL_PRIVATE_FLAGS);
                if (fieldInfo == null && targetType.BaseType != typeof(object))
                    return targetType.BaseType.LocateField(name);
                return fieldInfo;
            }
            catch (ArgumentException)
            {
                if (targetType.BaseType != typeof(object))
                {
                    return targetType.BaseType.LocateField(name);
                }
                throw;
            }
        }
}

Related Tutorials