tags:

views:

175

answers:

4
 [FlagsAttribute]
public enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 };

I have an enum as show. I want the ability to get say Colors.Blue is at index 2, index staring from 0.I want to get the index number passing in Colors.Whatever? Can someone post me some snippets...

+2  A: 

Can't really understand your question, but is this what you mean:

var blue = (Colors)Enum.GetValues(typeof(Colors))[2];

HTH, Kent

Kent Boogaart
You will get Cannot apply indexing with [] to an expression of type 'System.Array' ;)
ArsenMkrt
+2  A: 

Assuming that each color uses a single bit as value, you can just locate the index of that bit.

public int GetIndex(Colors color) {
   int value = (int)colors;
   int index = 0;
   while (value > 0) {
      value >>= 1;
      index++;
   }
   return index;
}

Note that the index of bits is normally zero based, but here you get a one based index.

If you want a zero based index, you would get the index two for blue, not three as you stated in the question. Just start with index = -1; if that is the result that you desire.

Guffa
sorry for the index, I have now changed it to 2
chugh97
+7  A: 

Try this one:

int index  = Array.IndexOf(Enum.GetValues(typeof(Colors )), Colors.Green);
Frank Bollack
A: 

I don't know why you need it , but one way to do that is

 Colors c = (Colors)Enum.Parse(typeof(Colors), Enum.GetNames(typeof(Colors))[index]);
ArsenMkrt