Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get numeric position of an enum in its definition list?

Tags:

c#

enums

I need to get the numeric position of an enum in its definition. Consider the following enum - it is used for bit fields but the status names would be useful if they had the values on the right that I have commented.

[Flags]
public enum StatusFlags
{
    None = 0,                 // 0  -- these commented indexes are the numbers I also would like
    Untested = 1,             // 1     to associate with the enum names.
    Passed_Programming = 2,   // 2
    Failed_Programming = 4,   // 3
    // ... many more
}

I have created a static method as follows, which works for what I want.

public static int GetStatusID(this StatusFlags flag)
{
   int i = 0;
   foreach (StatusFlags val in Enum.GetValues(typeof(StatusFlags)))
   {
      if (flag == val) break;
      i++;
   }
   return i;
}

It is used like this:

StatusFlags f = StatusFlags.Failed_Programming;

// I want the position i.e value of 3 not the value the enum is associated with i.e 4
int Index = f.GetStatusID();

Is there is a better way to do this?

like image 224
user2425056 Avatar asked Oct 31 '25 22:10

user2425056


1 Answers

How about using attributes on your enum? Something like this:

[Flags]
public enum StatusFlags
{
    [Index=0]
    None = 0,

    [Index=1]             
    Untested = 1,            

    [Index=2]
    Passed_Programming = 2,

    [Index=3]  
    Failed_Programming = 4,
    // ... many more
}

Then you can the index value of your enum like this:

var type = typeof(StatusFlags);
var statusFlag = type.GetMember(StatusFlags.Untested.ToString());
var attributes = statusFlag [0].GetCustomAttributes(typeof(IndexAttribute),false);
var index = int.Parse(((IndexAttribute)attributes[0]).Index); //if you need an int value
like image 67
Chris Avatar answered Nov 03 '25 12:11

Chris



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!