Skip to content

Instantly share code, notes, and snippets.

@jwatney
Created June 1, 2017 18:19
Show Gist options
  • Save jwatney/fa9cfc51ee222e4849b7012b398cb50f to your computer and use it in GitHub Desktop.
Save jwatney/fa9cfc51ee222e4849b7012b398cb50f to your computer and use it in GitHub Desktop.
StringConverter
public static class StringConverter {
public static T To<T>(this string value) {
if(String.IsNullOrEmpty(value)) {
return default(T);
}
try {
var convertibleValue = (IConvertible)value;
var conversionType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
return (T)convertibleValue.ToType(conversionType, CultureInfo.CurrentCulture);
} catch(InvalidCastException) {
} catch(FormatException) {
}
return default(T);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment