Skip to content

Instantly share code, notes, and snippets.

@kwestground
Last active December 22, 2016 12:47
Show Gist options
  • Save kwestground/562d5877af38c0f526f7040b462675fd to your computer and use it in GitHub Desktop.
Save kwestground/562d5877af38c0f526f7040b462675fd to your computer and use it in GitHub Desktop.
TypeConverter
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