Get and Set Reflected Property Value
Here are a couple of handy C# extension methods I’ve created at work to get and set reflected property values.
Required Namespaces:
1 2 | using System; using System.Reflection; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | public static object GetReflectedPropertyValue(this object obj, string propertyName) { if (obj == null) { return new InvalidOperationException("The object does not have a value."); } Type t = obj.GetType(); PropertyInfo property = t.GetProperty(propertyName); if (property != null) { return property.GetValue(obj, null); } FieldInfo field = t.GetField(propertyName); if (field != null) { return field.GetValue(obj); } return null; } public static void SetReflectedPropertyValue(this object obj, string propertyName, object value) { if (obj == null) { throw new InvalidOperationException("The object does not have a value."); } Type t = obj.GetType(); PropertyInfo property = t.GetProperty(propertyName); if (property != null) { property.SetValue(obj, value, null); return; } FieldInfo field = t.GetField(propertyName); if (field != null) { field.SetValue(obj, value); return; } } |