Skip to content

Instantly share code, notes, and snippets.

@jonathascosta
Forked from juanplopes/gist:987646
Created May 23, 2011 21:41
Show Gist options
  • Save jonathascosta/987676 to your computer and use it in GitHub Desktop.
Save jonathascosta/987676 to your computer and use it in GitHub Desktop.
String Extensions
public static class TypeExtensions
{
public static Type GetValueTypeIfNullable(this Type type)
{
return type.IsNullable() ? type.GetGenericArguments()[0] : type;
}
public static bool IsNullable(this Type type)
{
return (type.IsGenericType && typeof(Nullable<>) == type.GetGenericTypeDefinition());
}
}
public static class StringExtensions
{
public static object ToType(this string origin, Type type)
{
if (type.IsNullable() && string.IsNullOrEmpty(origin))
return null;
var realType = type.GetValueTypeIfNullable();
if (typeof(IConvertible).IsAssignableFrom(realType))
return Convert.ChangeType(origin, realType);
return origin;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment