How can I get the max int value from an enum using generics?
I have tried the following however it displays the following compilation error:
Cannot implicitly convert T to int
int maxValue = GetMaxValue<SomeEnum>(typeof(SomeEnum)); //expecting 2
private static int GetMaxValue<T>(Type enumType)
{
return Enum.GetValues(enumType).Cast<T>().Max();
}
public enum SomeEnum
{
ValueOne = 1,
Value = 2
}
In case of C# 7.3 or later version, you can implement Sweeper's idea in a bit different way (with a help of where T : Enum constraint):
public static T GetMaxValue<T>() where T : Enum {
return Enum.GetValues(typeof(T)).Cast<T>().Max();
}
...
SomeEnum max = GetMaxValue<SomeEnum>();
Please, note, that the result is enum itself and that's why we don't have any problems with enum underlying type (byte, short int, long)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With