I have the following code. I need to create a List from KeyValuePair<string, string> with the name and value of each enum value in the specified enum type.
public static List<KeyValuePair<string, string>> GetEnumList<TEnum>() where TEnum : struct { if (!typeof(TEnum).IsEnum) throw new ArgumentException("Type must be an enumeration"); List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>(); foreach (TEnum e in Enum.GetValues(typeof(TEnum))) list.Add(new KeyValuePair<string, string>(e.ToString(), ((int)e).ToString())); return list; }
However, the expression ((int)e).ToString() generates the following error.
Cannot convert type 'TEnum' to 'int'
I'm just trying to use an enum instance for an integer. Can someone tell me why this will not work?
EDIT:
I tried this version:
enum Fruit : short { Apple, Banana, Orange, Pear, Plum, } void Main() { foreach (var x in EnumHelper.GetEnumList<Fruit>()) Console.WriteLine("{0}={1}", x.Value, x.Key); } public static List<KeyValuePair<string, string>> GetEnumList<TEnum>() where TEnum : struct { if (!typeof(TEnum).IsEnum) throw new ArgumentException("Type must be an enumeration"); List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>(); foreach (TEnum e in Enum.GetValues(typeof(TEnum))) { list.Add(new KeyValuePair<string, string>(e.ToString(), ((int)(dynamic)e).ToString())); } return list; }
But this gives me an error:
Cannot convert type 'System.Enum' to 'int'
source share