I think that you are fighting, it is a search for a description. I am sure that as soon as you have those that you can determine by your final method, which gives your exact result.
First, if you define an extension method, it works on the value of the enumeration, and not on the type of enumeration itself. And I think for convenience you would like to call a type method (e.g. static method). Unfortunately, you cannot define them.
What you can do is the following. First, define a method that retrieves a description of the enumeration value, if it has one:
public static string GetDescription(this Enum value) { string description = value.ToString(); FieldInfo fieldInfo = value.GetType().GetField(description); DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes != null && attributes.Length > 0) { description = attributes[0].Description; } return description; }
Then define a method that takes all the values of the enumeration, and use the previous method to find the value that we want to show, and return this list. The general argument can be inferred.
public static List<KeyValuePair<TEnum, string>> ToEnumDescriptionsList<TEnum>(this TEnum value) { return Enum .GetValues(typeof(TEnum)) .Cast<TEnum>() .Select(x => new KeyValuePair<TEnum, string>(x, ((Enum)((object)x)).GetDescription())) .ToList(); }
And finally, for ease of use, the method for direct invocation without value. But then the general argument is not optional.
public static List<KeyValuePair<TEnum, string>> ToEnumDescriptionsList<TEnum>() { return ToEnumDescriptionsList<TEnum>(default(TEnum)); }
Now we can use it as follows:
enum TestEnum { [Description("My first value")] Value1, Value2, [Description("Last one")] Value99 } var items = default(TestEnum).ToEnumDescriptionsList();
What outputs:
Value1 - My first value Value2 - Value2 Value99 - Last one