C# Enum to List Conversion

Sometimes we need to display all the enum options on user interface, so that end user can select some item from options, to do that, we need to convert the enum to a list object.

Here we learn, how to convert Enum to List in C# .Net programming.

Enum to List in C#

Here is my enum EventState, now i want to display in UI as a list object in dropdown control, So i need to convert the enum to a list object

enum EventState            
{
    Initiated = 1,
    Started = 2,
    Closed = 3,
    Canceled = 4
}

This is a static method that converts enum to a generic List type

public static List<T> EnumToList<T>()        
{
    Type enumType = typeof(T);
        
    // You can't use type constraints on value types, so have to check & throw error.
    if (enumType.BaseType != typeof(Enum))
    throw new ArgumentException("T must be of type System.Enum type");
        
    Array enumValArray = Enum.GetValues(enumType);
        
    List<T> enumValList = new List<T>(enumValArray.Length);
        
    foreach (int val in enumValArray)
    {
    enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
    }
        
return enumValList;
}

Finally, call the above method, pass enum as parameter to get the List

        public static List<EventState> GetEventStates()
        {
        List<EventState> eventStates = EnumToList<EventState>();
        
        return eventStates;
        }

Learn more about C# Enums in .Net

.Net C# Examples | Join .Net C# Course