Skip to content

Instantly share code, notes, and snippets.

@Sl4vP0weR
Created January 6, 2022 21:50
Show Gist options
  • Save Sl4vP0weR/c665da3a2350b0dc800618191cb47f2d to your computer and use it in GitHub Desktop.
Save Sl4vP0weR/c665da3a2350b0dc800618191cb47f2d to your computer and use it in GitHub Desktop.
Extension that allows you to convert IConvertible by generic
public static T To<T>(this IConvertible convertible)
where T : IConvertible
{
if (convertible is null)
return default;
var convertMethod = typeof(IConvertible).GetMethod($"To{typeof(T).Name}");
if (convertMethod is null)
throw new ArgumentException($"{convertible.GetType().Name} can't be converted to {typeof(T).Name}");
var value = convertMethod.Invoke(convertible, new object[] { null });
return (T)value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment