5

Here's a "weird" question:

Is it possible to create a method where in it will convert whatever enum to list. Here's my draft of what I'm currently thinking.

public class EnumTypes
{
   public enum Enum1
   {
      Enum1_Choice1 = 1,
      Enum1_Choice2 = 2
   }

   public enum Enum2
   {
      Enum2_Choice1 = 1,
      Enum2_Choice2 = 2
   }

   public List<string> ExportEnumToList(<enum choice> enumName)
   {
      List<string> enumList = new List<string>();
      //TODO: Do something here which I don't know how to do it.
      return enumList;
   }
}

Just curious if it's possible and how to do it.

Musikero31
  • 3,115
  • 6
  • 39
  • 60

2 Answers2

11
Enum.GetNames( typeof(EnumType) ).ToList()

http://msdn.microsoft.com/en-us/library/system.enum.getnames.aspx

Or, if you want to get fancy:

    public static List<string> GetEnumList<T>()
    {
        // validate that T is in fact an enum
        if (!typeof(T).IsEnum)
        {
            throw new InvalidOperationException();
        }

        return Enum.GetNames(typeof(T)).ToList();
    }

    // usage:
    var list = GetEnumList<EnumType>();
Moho
  • 15,457
  • 1
  • 30
  • 31
0
public List<string> ExportEnumToList(<enum choice> enumName)    {
List<string> enumList = new List<string>();
//TODO: Do something here which I don't know how to do it.
foreach (YourEnum item in Enum.GetValues(typeof(YourEnum ))){
    enumList.Add(item);
}
return enumList;    

}

mihai
  • 2,746
  • 3
  • 35
  • 56