From 39264cc1abf1b6548d134cb78c72b3b0ab55d8db Mon Sep 17 00:00:00 2001 From: David Hall Date: Tue, 9 Apr 2019 09:16:59 -0600 Subject: [PATCH] Separated GetPropertyValue into 2 separate methods and removed type changing to prevent unintended consequences. --- Core/Extensions/ReflectionExtensions.cs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/Core/Extensions/ReflectionExtensions.cs b/Core/Extensions/ReflectionExtensions.cs index 95d85523..ac7d556d 100644 --- a/Core/Extensions/ReflectionExtensions.cs +++ b/Core/Extensions/ReflectionExtensions.cs @@ -61,16 +61,26 @@ namespace Vanara.Extensions bool ImplIEnumT(Type t) => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>); } + /// Gets a named property value from an object. + /// The expected type of the property to be returned. + /// The object from which to retrieve the property. + /// Name of the property. + /// The property value. + public static T GetPropertyValue(this object obj, string propertyName) + { + if (obj is null) throw new ArgumentNullException(nameof(obj)); + return (T)obj.GetType().InvokeMember(propertyName, BindingFlags.GetProperty | bindingFlags, null, obj, null, null); + } + /// Gets a named property value from an object. /// The expected type of the property to be returned. /// The object from which to retrieve the property. /// Name of the property. /// The default value to return in the instance that the property is not found. /// The property value, if found, or the if not. - public static T GetPropertyValue(this object obj, string propertyName, T defaultValue = default) + public static T GetPropertyValue(this object obj, string propertyName, T defaultValue) { - if (obj is null || propertyName is null) return defaultValue; - try { return (T)Convert.ChangeType(obj.GetType().InvokeMember(propertyName, BindingFlags.GetProperty | bindingFlags, null, obj, null, null), typeof(T)); } + try { return GetPropertyValue(obj, propertyName); } catch { return defaultValue; } }