Getting the max value of an enum

Viewed 106916

How do you get the max value of an enum?

11 Answers

Enum.GetValues() seems to return the values in order, so you can do something like this:

// given this enum:
public enum Foo
{
    Fizz = 3, 
    Bar = 1,
    Bang = 2
}

// this gets Fizz
var lastFoo = Enum.GetValues(typeof(Foo)).Cast<Foo>().Last();

Edit

For those not willing to read through the comments: You can also do it this way:

var lastFoo = Enum.GetValues(typeof(Foo)).Cast<Foo>().Max();

... which will work when some of your enum values are negative.

This is slightly nitpicky but the actual maximum value of any enum is Int32.MaxValue (assuming it's a enum derived from int). It's perfectly legal to cast any Int32 value to an any enum regardless of whether or not it actually declared a member with that value.

Legal:

enum SomeEnum
{
    Fizz = 42
}

public static void SomeFunc()
{
    SomeEnum e = (SomeEnum)5;
}

In agreement with Matthew J Sullivan, for C#:

   Enum.GetValues(typeof(MyEnum)).GetUpperBound(0);

I'm really not sure why anyone would want to use:

   Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Last();

...As word-for-word, semantically speaking, it doesn't seem to make as much sense? (always good to have different ways, but I don't see the benefit in the latter.)

I used the following when I needed the min and max values of my enum. I just set a min equal to the lowest value of the enumeration and a max equal to the highest value in the enumeration as enum values themselves.

public enum ChannelMessageTypes : byte
{
    Min                 = 0x80, // Or could be: Min = NoteOff
    NoteOff             = 0x80,
    NoteOn              = 0x90,
    PolyKeyPressure     = 0xA0,
    ControlChange       = 0xB0,
    ProgramChange       = 0xC0,
    ChannelAfterTouch   = 0xD0,
    PitchBend           = 0xE0,
    Max                 = 0xE0  // Or could be: Max = PitchBend
}

// I use it like this to check if a ... is a channel message.
if(... >= ChannelMessageTypes.Min || ... <= ChannelMessages.Max)
{
    Console.WriteLine("Channel message received!");
}

It is not usable in all circumstances, but I often define the max value myself:

enum Values {
  one,
  two,
  tree,
  End,
}

for (Values i = 0; i < Values.End; i++) {
  Console.WriteLine(i);
}

var random = new Random();
Console.WriteLine(random.Next((int)Values.End));

Of course this won't work when you use custom values in an enum, but often it can be an easy solution.

Related