Essential
Essential

Reputation: 421

Address custom enum values by order

Usually I can address each item in an enum by it's ordered position (0, 1, 2, 3...), but if I've created an enum with custom values (as below), is there still a way to address each item by its declared order (e.g., Off = 0, _5m = 1, _15m = 2, etc.), rather than its value?

enum WaitTime { Off = 0, _5m = 5, _15m = 15, _30m = 30, _1h = 60, _2h = 120, _3h = 180, _6h = 360, _12h = 720, _1d = 1440, _2d = 2880 }

Upvotes: 1

Views: 144

Answers (3)

quantdev
quantdev

Reputation: 23813

(Answer for C#)

No you wont, e.g. _5m converts to 5, not to 1.

What you call "order" is an implicit conversion to an integer (which by default is 0 ... N-1 for an enum with N values)

enum WaitTime { Off = 0, _5m = 5, _15m = 15, _30m = 30, _1h = 60, _2h = 120, _3h = 180, _6h = 360, _12h = 720, _1d = 1440, _2d = 2880 }

class Program
{
    static void Main()
    {
        WaitTime wt = WaitTime._15m;
        Console.WriteLine((int)wt);
    }
}

Will output 15.

PS.: avoid leading underscores when declaring your enum values.

Upvotes: 0

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26665

In C# You can use Enum.GetValues() method.

It retrieves an array of the values of the constants in a specified enumeration. The elements of the array are sorted by the binary values of the enumeration constants.

Array enumElementsInArray = Enum.GetValues(typeof(WaitTime));

int firstElement = enumElementsInArray[0];
int secondElement = enumElementsInArray[1];

But know that, it will return the aray after sorting elements by their values. But of course, for your enum it will work as you want.

Upvotes: 2

Flat Eric
Flat Eric

Reputation: 8111

This would be a generic way that works for all types of enums:

public static T GetValueAt<T>(int idx)
{
  var vals = Enum.GetValues(typeof(T));
  return (T)vals.GetValue(idx);
}

Usage:

var value = GetValueAt<WaitTime>(2); //returns _15m

Upvotes: 1

Related Questions