Skip to content

Instantly share code, notes, and snippets.

@bymyslf
Last active November 4, 2016 15:00
Show Gist options
  • Save bymyslf/ad22d6211a42e20f2522fcdbfc6cea20 to your computer and use it in GitHub Desktop.
Save bymyslf/ad22d6211a42e20f2522fcdbfc6cea20 to your computer and use it in GitHub Desktop.
using System;
public static class ConvertExtensions
{
public static T To<T>(this object obj)
{
try
{
Type type = typeof(T);
if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
if (obj == null)
{
return (T)(object)null;
}
return (T)Convert.ChangeType(obj, Nullable.GetUnderlyingType(type));
}
if (typeof(Enum).IsAssignableFrom(type))
{
return ConvertToEnum<T>(obj);
}
return ConvertTo<T>(obj);
}
catch (Exception ex)
{
}
return default(T);
}
private static T ConvertToEnum<T>(object obj)
{
Type type = typeof(T);
if (obj is string)
{
return (T)Enum.Parse(type, (string)obj, true);
}
return (T)Enum.ToObject(type, obj);
}
private static T ConvertTo<T>(object obj)
{
if (obj.IsNull())
{
return default(T);
}
Type type = typeof(T);
TypeConverter converter = TypeDescriptor.GetConverter(type);
if (converter.IsNotNull() && converter.CanConvertFrom(obj.GetType()))
{
return (T)converter.ConvertFrom(obj);
}
return (T)Convert.ChangeType(obj, type);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment