Skip to content

Instantly share code, notes, and snippets.

@NDiiong
Created May 22, 2021 11:09
Show Gist options
  • Save NDiiong/ab316a020f5d7f841ffb90402d0272b9 to your computer and use it in GitHub Desktop.
Save NDiiong/ab316a020f5d7f841ffb90402d0272b9 to your computer and use it in GitHub Desktop.
public static T To<T>(this object obj)
where T : struct
{
if (typeof(T) == typeof(Guid) || typeof(T) == typeof(TimeSpan))
{
return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(obj.ToString());
}
if (typeof(T).IsEnum)
{
if (Enum.IsDefined(typeof(T), obj))
{
return (T)Enum.Parse(typeof(T), obj.ToString());
}
else
{
throw new ArgumentException($"Enum type undefined '{obj}'.");
}
}
return (T)Convert.ChangeType(obj, typeof(T), CultureInfo.InvariantCulture);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment