diff --git a/ICD.Common.Utils.Tests/ReflectionUtilsTest.cs b/ICD.Common.Utils.Tests/ReflectionUtilsTest.cs index 81b34d9..21adc45 100644 --- a/ICD.Common.Utils.Tests/ReflectionUtilsTest.cs +++ b/ICD.Common.Utils.Tests/ReflectionUtilsTest.cs @@ -121,9 +121,33 @@ namespace ICD.Common.Utils.Tests } [Test] - public void LoadAssemblyFromPath() + public void LoadAssemblyFromPathTest() { Assert.Inconclusive(); } + + [Test] + public void GetImplementationTest() + { + Assert.Inconclusive(); + } + + [Test] + public void ChangeTypeTest() + { + // Same type + Assert.AreEqual(10, ReflectionUtils.ChangeType(10, typeof(int))); + + // Null + Assert.AreEqual(null, ReflectionUtils.ChangeType(null, typeof(string))); + + // Enums + Assert.AreEqual(BindingFlags.GetProperty, ReflectionUtils.ChangeType((int)(object)BindingFlags.GetProperty, typeof(BindingFlags))); + Assert.AreEqual(BindingFlags.GetProperty, ReflectionUtils.ChangeType(BindingFlags.GetProperty.ToString(), typeof(BindingFlags))); + Assert.AreEqual(BindingFlags.GetProperty, ReflectionUtils.ChangeType(((int)(object)BindingFlags.GetProperty).ToString(), typeof(BindingFlags))); + + // Everything else + Assert.AreEqual(10, ReflectionUtils.ChangeType("10", typeof(int))); + } } } diff --git a/ICD.Common.Utils/ReflectionUtils.cs b/ICD.Common.Utils/ReflectionUtils.cs index cdf400a..2a4733d 100644 --- a/ICD.Common.Utils/ReflectionUtils.cs +++ b/ICD.Common.Utils/ReflectionUtils.cs @@ -368,5 +368,42 @@ namespace ICD.Common.Utils ? property : GetImplementation(property.DeclaringType, property); } + + /// + /// Changes the given value to the given type. + /// + /// + /// + /// + public static object ChangeType(object value, Type type) + { + if (type == null) + throw new ArgumentNullException("type"); + + // Handle null value + if (value == null) + { + if (type.CanBeNull()) + return null; + + throw new InvalidCastException(); + } + + Type valueType = value.GetType(); + if (valueType.IsAssignableTo(type)) + return value; + + // Handle enum + if (type.IsEnum) + { + if (valueType.IsIntegerNumeric()) + return Enum.ToObject(type, value); + + if (value is string) + return Enum.Parse(type, value as string, false); + } + + return Convert.ChangeType(value, type, null); + } } }