Using a generic list to hold various Enum types

  • Thread starter Thread starter T Gregory
  • Start date Start date
T

T Gregory

Guest
I have a need to display certain Enums as a list so they can be added to a ComboBox. What I've been doing is creating a property for each Enum that turns each element of the Enum into an item in a list. It works great, but I'd rather just have one function that outputs a list based on whatever Enum I send it.

For example, here's how I do it now for an Enum named Importance:

public List<Importance> ImportanceTypes
{
get
{
List<Importance> importanceTypes = new List<Importance>();

foreach (string importanceType in Enum.GetNames(typeof(Importance)))
{
importanceTypes.Add((Importance)Enum.Parse(typeof(Importance), importanceType));
}

return importanceTypes;
}
}


What I'd like to have is something like this, where GenericEnumType is whatever Enum I want it to be...

public static List<GenericEnumType> EnumToList(GenericEnumType genericEnumType) {
List<genericEnumType> enumTypes = new List<genericEnumType>();

foreach (string enumType in Enum.GetNames(typeof(genericEnumType))) {

enumTypes.Add((genericEnumType)Enum.Parse(typeof(genericEnumType), enumType));

}

return enumTypes;
}


And then I can just feed that function an Enum type and get a List to populate ComboBoxes, etc... with.


Is there a good way to allow for generic Enums in a function like that?

Continue reading...
 
Back
Top