Created
January 6, 2022 21:50
-
-
Save Sl4vP0weR/c665da3a2350b0dc800618191cb47f2d to your computer and use it in GitHub Desktop.
Extension that allows you to convert IConvertible by generic
This file contains 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 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