I am making several drop down lists from enums. For example, the length of a lunchbreak enum will add dropdown list items like this:
foreach (LunchBreak type in Enum.GetValues(typeof(LunchBreak)))
{
items.Add(new SelectListItem()
{
Text = SiteUtilities.GetEnumDescription(type),
Value = ((int)type).ToString()
});
}
Where my enum is in the form of:
public enum LunchBreak : int
{
[Description("20 minutes paid")]
Paid_20 = 0,
[Description("20 minutes unpaid")]
Unpaid_20 = 1
}
Is there a way to make that foreach loop generic so I can pass in typeof(LunchBreak)
so I don't have to redo the code for all the other enums?
I tried writing it where I could just pass in LunchBreak
but then it complained about me using the enum as a Type.
I tried to do an extension method like here so I could call something like LunchBreak.GetSelectListItems("Please select a lunch break...")
and had a look at several posts like this: Create Generic method constraining T to an Enum but didn't really get what was going on
Extension attempt:
public static class EnumExtensions
{
public static List<SelectListItem> GetSelectListItems<T>(string defaultValue) where T : struct, IConvertible
{
if (typeof(T).IsEnum)
{
List<SelectListItem> items = new List<SelectListItem>()
{
new SelectListItem()
{
Text = defaultValue,
Value = string.Empty
}
};
foreach (T item in Enum.GetValues(typeof(T)))
{
items.Add(new SelectListItem()
{
Text = SiteUtilities.GetEnumDescription(item), // this line fails as item is expected to be of type Enum
Value = ((int)item).ToString() // this line fails as I can't cast item as an int
});
}
return items;
}
throw new ArgumentException("T must be an enumerated type");
}
}