I have various enums that I use as sources for dropdown lists, In order to provide for a user-friendly description, I added a Description
attribute to each enum, an
What is the correct way to use it as an extension (using the above 2 methods)?
There is no correct way to use it as an extension. Extension methods (similar to instance methods) are used when you have a value (instance) and for instance want to get some information related to that value. So the extension method would make sense if you want to get the description of a single enum
value.
However, in your case the information you need (the list of enum
value/description pairs) is not tied to a specific enum
value, but to the enum
type. Which means you just need a plain static generic method similar to Enum.TryParseenum
, but this type of constraint is not supported (yet), so we'll use (similar to the above system method) just where TEnum : struct
and will add runtime check.
So here is a sample implementation:
public static class EnumInfo
{
public static List> GetList()
where TEnum : struct
{
if (!typeof(TEnum).IsEnum) throw new InvalidOperationException();
return ((TEnum[])Enum.GetValues(typeof(TEnum)))
.ToDictionary(k => k, v => ((Enum)(object)v).GetAttributeOfType().Description)
.ToList();
}
}
and usage:
public enum MyEnum
{
[Description("Foo")]
A,
[Description("Bar")]
B,
[Description("Baz")]
C,
}
var list = EnumInfo.GetList();