Last active
December 22, 2016 12:47
-
-
Save kwestground/562d5877af38c0f526f7040b462675fd to your computer and use it in GitHub Desktop.
TypeConverter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ComponentModel; | |
using System.Globalization; | |
public static class TypeConverter | |
{ | |
public static T To<T>(this object value) | |
{ | |
return (T)To(value, typeof(T)); | |
} | |
private static object To(object value, Type destinationType) | |
{ | |
return To(value, destinationType, CultureInfo.InvariantCulture); | |
} | |
private static object To(object value, Type destinationType, CultureInfo culture) | |
{ | |
if (value == null) | |
return destinationType.IsValueType ? Activator.CreateInstance(destinationType) : null; | |
var sourceType = value.GetType(); | |
var destinationConverter = GetTypeConverter(destinationType); | |
var sourceConverter = GetTypeConverter(sourceType); | |
if (destinationConverter != null && destinationConverter.CanConvertFrom(value.GetType())) | |
return destinationConverter.ConvertFrom(null, culture, value); | |
if (sourceConverter != null && sourceConverter.CanConvertTo(destinationType)) | |
return sourceConverter.ConvertTo(null, culture, value, destinationType); | |
if (destinationType.IsEnum && value is int) | |
return Enum.ToObject(destinationType, (int)value); | |
if (!destinationType.IsInstanceOfType(value)) | |
return Convert.ChangeType(value, destinationType, culture); | |
return value; | |
} | |
private static TypeConverter GetTypeConverter(Type type) | |
{ | |
return TypeDescriptor.GetConverter(type); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment