Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get max value from enum using generics

Tags:

c#

enums

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
    }
like image 516
David Klempfner Avatar asked Apr 19 '26 13:04

David Klempfner


1 Answers

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)

like image 118
Dmitry Bychenko Avatar answered Apr 22 '26 01:04

Dmitry Bychenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!