Reputation: 9890
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
}
Upvotes: 3
Views: 468
Reputation: 186803
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
)
Upvotes: 3
Reputation: 272555
You need to cast to int
, not T
. And you don't actually need the Type
parameter (unless you don't know the type at compile time), since you can just do typeof(T)
:
private static int GetMaxValue<T>()
{
return Enum.GetValues(typeof(T)).Cast<int>().Max();
}
// usage:
GetMaxValue<SomeEnum>() // 2
If your enums have long
or some other type as the underlying type, you can specify another type parameter to cast them to:
private static U GetMaxValue<T, U>() where U : struct
{
return Enum.GetValues(typeof(T)).Cast<U>().Max();
}
// usage:
GetMaxValue<SomeLongEnum, long>()
Upvotes: 2
Reputation: 27156
Use Convert.ToInt32
return Convert.ToInt32(Enum.GetValues(enumType).Cast<T>().Max());
But usually I do this, more faster than calling GetValues
public enum SomeEnum
{
ValueOne = 1,
Value = 2,
END
}
return (int)(SomeEnum.END - 1);
Upvotes: 0