Object - GetPropertyValue
A T extension method that gets property value.
public static void Main() { var obj = new PropertyModel<int>() { PublicProperty = 3 }; //C# Extension Method: Object - GetPropertyValue Console.WriteLine(obj.GetPropertyValue("PublicProperty")); obj.PublicProperty = 5; //C# Extension Method: Object - GetPropertyValue Console.WriteLine(obj.GetPropertyValue("PublicProperty")); } public class PropertyModel<T> : AbstractPropertyModel { public static int StaticProperty { get; set; } public override int OverrideProperty { get; set; } public virtual int VirtualProperty { get; set; } internal int InternalProperty { get; set; } private int PrivateProperty { get; set; } protected int ProtectedProperty { get; set; } protected internal int ProtectedInternalProperty { get; set; } public int PublicProperty { get; set; } public int PublicGetterPrivateSetterProperty { get; private set; } public int PrivateGetterPublicSetterProperty { private get; set; } public T GenericProperty { get; set; } public T this[T param1, int param2] { get { return param1; }} public override int AbstractProperty { get; set; } } public abstract class AbstractPropertyModel { public abstract int AbstractProperty { get; set; } public virtual int OverrideProperty { get; set; } }
View Source
using System; using System.Reflection; public static partial class Extensions { /// <summary> /// A T extension method that gets property value. /// </summary> /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="this">The @this to act on.</param> /// <param name="propertyName">Name of the property.</param> /// <returns>The property value.</returns> public static object GetPropertyValue<T>(this T @this, string propertyName) { Type type = @this.GetType(); PropertyInfo property = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); return property.GetValue(@this, null); } }