Skip to content

Instantly share code, notes, and snippets.

@NDiiong
Last active April 29, 2021 11:12
Show Gist options
  • Save NDiiong/948e19d4d10e3655b234c599418cc593 to your computer and use it in GitHub Desktop.
Save NDiiong/948e19d4d10e3655b234c599418cc593 to your computer and use it in GitHub Desktop.
public static class ParseExtension
{
private static CultureInfo _cultureInfo = CultureInfo.CurrentCulture;
public static T As<T>(this object value)
{
var toType = typeof(T);
if (value == null) return default(T);
if (value is string)
{
if (toType == typeof(Guid))
return As<T>(new Guid(Convert.ToString(value, _cultureInfo)), _cultureInfo);
if ((string)value == string.Empty && toType != typeof(string))
return As<T>(null, _cultureInfo);
}
else
{
if (typeof(T) == typeof(string))
return As<T>(Convert.ToString(value, _cultureInfo), _cultureInfo);
}
if (toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(Nullable<>))
toType = Nullable.GetUnderlyingType(toType);
var canConvert = toType is IConvertible || (toType.IsValueType && !toType.IsEnum);
if (canConvert)
return (T)Convert.ChangeType(value, toType, _cultureInfo);
return (T)value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment