-
-
Save jonathascosta/987676 to your computer and use it in GitHub Desktop.
String Extensions
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
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