How can I get a List of an Enum's values?
For example, I have the following:
public enum ContactSubjects
{
[Description("General Question")]
General,
[Description("Availability/Reservation")]
Reservation,
[Description("Other Issue")]
Other
}
What I need to be able to do is pass ContactSubject.General as an argument and it returns the List of the descriptions.
This method needs to work with any Enum, not just ContactSubject (in my example). The signature should be something like GetEnumDescriptions(Enum value).
Something like that may work:
private static IEnumerable<string> GetDescriptions(Type type)
{
var descs = new List<string>();
var names = Enum.GetNames(type);
foreach (var name in names)
{
var field = type.GetField(name);
var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
foreach (DescriptionAttribute fd in fds)
{
descs.Add(fd.Description);
}
}
return descs;
}
however you may review some logic there: such as is it ok to start of names? how are you going to handle multiple Description attributes? What if some of them are missing - do you want a name or just skip it like above? etc.
just reviewed your question. For the VALUE you would have something like that:
private static IEnumerable<string> GetDescriptions(Enum value)
{
var descs = new List<string>();
var type = value.GetType();
var name = Enum.GetName(type, value);
var field = type.GetField(name);
var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
foreach (DescriptionAttribute fd in fds)
{
descs.Add(fd.Description);
}
return descs;
}
however it is not possible to place two Description attributes on single field, so I guess it may return just string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With