Example #1
0
        /// <summary>
        /// Set an object's readonly property value using reflection.
        /// </summary>
        /// <param name="source">The object to set the property on.</param>
        /// <param name="propertyName">Property name.</param>
        /// <param name="value">Property value.</param>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="source" /> is null.</exception>
        /// <exception cref="T:System.ArgumentException"><paramref name="propertyName" /> is null or empty.</exception>
        /// <exception cref="T:System.InvalidOperationException">Property does not exist.</exception>
        public static void SetPropertyReadOnlyValue(this object source, string propertyName, object value)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (string.IsNullOrEmpty(propertyName))
            {
                throw new ArgumentException("Property name is null or empty.", nameof(propertyName));
            }

            var fieldInfo = source.GetType().GetBackingField(propertyName);

            if (fieldInfo == null)
            {
                ExceptionThrower.ThrowPropertyDoesNotExist(source.GetType(), propertyName);
            }

            fieldInfo.SetValue(source, value);
        }
Example #2
0
        public static PropertyInfo GetPropertyInfoOrThrow(Type source, string propertyName, bool ignoreCase, BindingFlags flags)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (string.IsNullOrEmpty(propertyName))
            {
                throw new ArgumentException("Property name is null or empty.", nameof(propertyName));
            }

            var pi = ignoreCase ?
                     source.GetProperty(propertyName, flags | BindingFlags.IgnoreCase) :
                     source.GetProperty(propertyName, flags);

            if (pi == null)
            {
                ExceptionThrower.ThrowPropertyDoesNotExist(source, propertyName);
            }

            return(pi);
        }