views:

4394

answers:

8

I have the following code:

// Obtain the string names of all the elements within myEnum 
String[] names = Enum.GetNames( typeof( myEnum ) );

// Obtain the values of all the elements within myEnum 
Array values = Enum.GetValues( typeof( myEnum ) );

// Print the names and values to file
for ( int i = 0; i < names.Length; i++ )
{
    print( names[i], values[i] ); 
}

However, I cannot index values. Is there an easier way to do this?

Or have I missed something entirely!

+2  A: 

What about using a foreach loop, maybe you could work with that?

  int i = 0;
  foreach (var o in values)
  {
    print(names[i], o);
    i++;
  }

something like that perhaps?

TWith2Sugars
I have thaught of that ... but I need to get access to both names and values in 'sync' ... say the names[2] is paired with values[2] and I am unsure as to how to achieve this in a foreach loop!
TK
I've added an example - see if that helps.
TWith2Sugars
+8  A: 
Array values = Enum.GetValues(typeof(myEnum));

foreach( MyEnum val in values )
{
   Console.WriteLine (String.Format("{0}: {1}", Enum.GetName(typeof(MyEnum), val), val);
}

Or, you can cast the System.Array that is returned:

string[] names = Enum.GetNames(typeof(MyEnum));
MyEnum[] values = (MyEnum[])Enum.GetValues(typeof(MyEnum));

for( int i = 0; i < names.Length; i++ )
{
    print(names[i], values[i]);
}

But, can you be sure that GetValues returns the values in the same order as GetNames returns the names ?

Frederik Gheysels
"But, can you be sure that GetValues returns the values in the same order as GetNames returns the names ?" -- This is a very good point and something I have yet to address! I think your first solution would probably provide a way to match values and strings reliably
TK
Hello, I've seen mention before of this suspicion of "index-mismatching" occurring when doing this; however, I've yet to discover whether this really is a concern or not? Are there any definitive cases whereby this assumption may go awry? Thx!
Funka
+11  A: 

You need to cast the array - the returned array is actually of the requested type, i.e. myEnum[] if you ask for typeof(myEnum):

myEnum[] values = (myEnum[]) Enum.GetValues(typeof(myEnum));

Then values[0] etc

Marc Gravell
+2  A: 

You can cast that Array to different types of Arrays:

myEnum[] values = (myEnum[])Enum.GetValues(typeof(myEnum));

or if you want the integer values:

int[] values = (int[])Enum.GetValues(typeof(myEnum));

You can iterate those casted arrays of course :)

Arcturus
+1  A: 

How about a dictionary list?

Dictionary<string, int> list = new Dictionary<string, int>();
foreach( var item in Enum.GetNames(typeof(MyEnum)) )
{
    list.Add(item, (int)Enum.Parse(typeof(MyEnum), item));
}

and of course you can change the dictionary value type to whatever your enum values are.

Mohammadreza
I think that this would be the way to go, but unfortucatly the enum is in an area of code which I have no control over!
TK
+2  A: 

Array has a GetValue(Int32) method which you can use to retrieve the value at a specified index.

Array.GetValue

Bubblewrap
A: 

Here is a simple way to iterate through your custom Enum object

For Each enumValue As Integer In [Enum].GetValues(GetType(MyEnum))

 Print([Enum].GetName(GetType(MyEnum), enumValue).ToString)

Next

Chev
A: 

Here is another. We had a need to provide friendly names for our EnumValues. We used the System.ComponentModel.DescriptionAttribute to show a custom string value for each enum value.

public static class StaticClass
{
    public static string GetEnumDescription(Enum currentEnum)
    {
        string description = String.Empty;
        DescriptionAttribute da;

        FieldInfo fi = currentEnum.GetType().
                    GetField(currentEnum.ToString());
        da = (DescriptionAttribute)Attribute.GetCustomAttribute(fi,
                    typeof(DescriptionAttribute));
        if (da != null)
            description = da.Description;
        else
            description = currentEnum.ToString();

        return description;
    }

    public static List<string> GetEnumFormattedNames<TEnum>()
    {
        var enumType = typeof(TEnum);
        if (enumType == typeof(Enum))
            throw new ArgumentException("typeof(TEnum) == System.Enum", "TEnum");

        if (!(enumType.IsEnum))
            throw new ArgumentException(String.Format("typeof({0}).IsEnum == false", enumType), "TEnum");

        List<string> formattedNames = new List<string>();
        var list = Enum.GetValues(enumType).OfType<TEnum>().ToList<TEnum>();

        foreach (TEnum item in list)
        {
            formattedNames.Add(GetEnumDescription(item as Enum));
        }

        return formattedNames;
    }
}

In Use

 public enum TestEnum
 { 
        [Description("Something 1")]
        Dr = 0,
        [Description("Something 2")]
        Mr = 1
 }



    static void Main(string[] args)
    {

        var vals = StaticClass.GetEnumFormattedNames<TestEnum>();
    }

This will end returning "Something 1", "Something 2"

Kevin Castle
Only good if the descriptions are static... if your descriptions need to change based on an instance basis then this approach won't work.
vanslly