Created
June 1, 2017 18:19
-
-
Save jwatney/fa9cfc51ee222e4849b7012b398cb50f to your computer and use it in GitHub Desktop.
StringConverter
This file contains hidden or 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 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