From 0fd8d91850e3c26b51526e496c459cd91a5a2002 Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Mon, 9 Apr 2018 16:22:48 -0400 Subject: [PATCH] docs: Better exception messages when failing to convert type --- ICD.Common.Utils/ReflectionUtils.cs | 63 ++++++++++++++++------------- 1 file changed, 36 insertions(+), 27 deletions(-) diff --git a/ICD.Common.Utils/ReflectionUtils.cs b/ICD.Common.Utils/ReflectionUtils.cs index 8e661b9..1260bb6 100644 --- a/ICD.Common.Utils/ReflectionUtils.cs +++ b/ICD.Common.Utils/ReflectionUtils.cs @@ -195,6 +195,24 @@ namespace ICD.Common.Utils != null; } + /// + /// Platform independant delegate instantiation. + /// + /// + /// + /// + /// + public static Delegate CreateDelegate(Type type, object firstArgument, MethodInfo method) + { + return +#if SIMPLSHARP + CDelegate +#else + Delegate +#endif + .CreateDelegate(type, firstArgument, method); + } + /// /// Creates an instance of the given type, calling the default constructor. /// @@ -368,42 +386,33 @@ namespace ICD.Common.Utils if (type.CanBeNull()) return null; - throw new InvalidCastException(); + throw new InvalidCastException(string.Format("Unable to convert NULL to type {0}", type.Name)); } Type valueType = value.GetType(); if (valueType.IsAssignableTo(type)) return value; - // Handle enum - if (type.IsEnum) + try { - if (valueType.IsIntegerNumeric()) - return Enum.ToObject(type, 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); + if (value is string) + return Enum.Parse(type, value as string, false); + } + + return Convert.ChangeType(value, type, null); + } + catch (Exception e) + { + string valueString = valueType.ToString(); + string message = string.Format("Failed to convert {0} to type {1} - {2}", valueString, type, e.Message); + throw new InvalidCastException(message, e); } - - return Convert.ChangeType(value, type, null); - } - - /// - /// Platform independant delegate instantiation. - /// - /// - /// - /// - /// - public static Delegate CreateDelegate(Type type, object firstArgument, MethodInfo method) - { - return -#if SIMPLSHARP - CDelegate -#else - Delegate -#endif - .CreateDelegate(type, firstArgument, method); } } }