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

CSharp examples for System.Reflection:PropertyInfo

Description

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

Demo Code

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

public class Main{
        /// <summary>
        /// Sets a private property given by it's name on a specific object.
        /// </summary>
        /// <param name="target">The target object on which to set the property.</param>
        /// <param name="name">The name of the property to set.</param>
        /// <param name="value">The value to assign to the property.</param>
        /// <example>
        /// public void AsExtentionMethod()
        /// {
        ///   MyClass myObjectOfMyClass = new MyClass();
        ///   myObjectOfMyClass.SetPrivateProperty("MyProperty", "MyValue");
        /// }
        /// 
        /// public void AsStaticMethod()
        /// {
        ///   MyClass myObjectOfMyClass = new MyClass();
        ///   PrivateMembersHelper.SetPrivateProperty(myObjectOfMyClass, "MyProperty", "MyValue");
        /// }
        /// </example>
        public static void SetPrivateProperty(this object target, string name, object value)
        {
            PropertyInfo property = target.GetType().LocateProperty(name, true, false);
            property.SetValue(target, value, null);
        }
        #region Private Helpers.

        private static PropertyInfo LocateProperty(this Type targetType, string name, bool demandWrite, bool demandRead)
        {
            try
            {
                PropertyInfo propertyInfo = targetType.GetProperty(name, ALL_PRIVATE_FLAGS);

                if (targetType.BaseType != typeof(object))
                {
                    // ReSharper disable ConditionIsAlwaysTrueOrFalse
                    if ((demandRead && demandWrite) && (!propertyInfo.CanWrite || !propertyInfo.CanRead))
                        return targetType.BaseType.LocateProperty(name, demandWrite, demandRead);

                    if (demandWrite && !propertyInfo.CanWrite)
                        return targetType.BaseType.LocateProperty(name, demandWrite, demandRead);

                    if (demandRead && !propertyInfo.CanRead)
                        return targetType.BaseType.LocateProperty(name, demandWrite, demandRead);
                    // ReSharper restore ConditionIsAlwaysTrueOrFalse
                }

                return propertyInfo;
            }
            catch (ArgumentException)
            {
                if (targetType.BaseType != typeof(object))
                {
                    return targetType.BaseType.LocateProperty(name, demandWrite, demandRead);
                }
                throw;
            }
        }
}

Related Tutorials