I have a number of enums and need to get them as List<string>
objects in order to enumerate through them and hence made the GetEnumAsStrings<T>()
method.
But it seems to me there would be an easier way.
Is there not a built-in method to get an enum like this into a List<string>
?
using System;
using System.Collections.Generic;
namespace TestEnumForeach2312
{
class Program
{
static void Main(string[] args)
{
List<string> testModes = StringHelpers.GetEnumAsStrings<TestModes>();
testModes.ForEach(s => Console.WriteLine(s));
Console.ReadLine();
}
}
public static class StringHelpers
{
public static List<string> GetEnumAsStrings<T>()
{
List<string> enumNames = new List<string>();
foreach (T item in Enum.GetValues(typeof(TestModes)))
{
enumNames.Add(item.ToString());
}
return enumNames;
}
}
public enum TestModes
{
Test,
Show,
Wait,
Stop
}
}
Addendum:
Thanks everyone, very insightful. Since I ultimately needed this for Silverlight which doesn't seem to have GetValues()
or GetNames()
for enums, I made this method which I created from this method:
public static List<string> ConvertEnumToListOfStrings<T>()
{
Type enumType = typeof(T);
List<string> strings = new List<string>();
var fields = from field in enumType.GetFields()
where field.IsLiteral
select field;
foreach (FieldInfo field in fields)
{
object value = field.GetValue(enumType);
strings.Add(((T)value).ToString());
}
return strings;
}