public static class TypeConversionExtensions { #region Non-generic private static Object To(this Object @object, Type type, Boolean returnDefaultOnFailedConversion) { Type underlyingTypeOfNullable = Nullable.GetUnderlyingType(type); try { return Convert.ChangeType(@object, underlyingTypeOfNullable ?? type); } catch (Exception exception) { if (returnDefaultOnFailedConversion) return type.IsValueType ? Activator.CreateInstance(type) : null; String typeName = type.Name; if (underlyingTypeOfNullable != null) typeName += " of " + underlyingTypeOfNullable.Name; throw new InvalidCastException("Object can't be cast to " + typeName, exception); } } public static Object To(this Object @object, Type type) { return @object.To(type, returnDefaultOnFailedConversion: false); } public static Object ToOrDefault(this Object @object, Type type) { return @object.To(type, returnDefaultOnFailedConversion: true); } #endregion #region Generic private static T To(this Object @object, Boolean returnDefaultOnFailedConversion) { return (T)@object.To(typeof(T), returnDefaultOnFailedConversion); } public static T To (this Object @object) { return @object.To (returnDefaultOnFailedConversion: false); } public static T ToOrDefault (this Object @object) { return @object.To (returnDefaultOnFailedConversion: true); } #endregion }
Saturday 29 December 2012
Type conversion extension method
Converting types in C# can get verbose. For those like me, who can't help but try to reduce the verbosity of their code, I pieced together this set of extension methods to make type conversion as clean as possible.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment