Search code examples
c#.netenumsgeneric-list

Convert an enum to List<string>


How do I convert the following Enum to a List of strings?

[Flags]
public enum DataSourceTypes
{
    None = 0,
    Grid = 1,
    ExcelFile = 2,
    ODBC = 4
};

I couldn't find this exact question, this Enum to List is the closest but I specifically want List<string>?


Solution

  • Use Enum's static method, GetNames. It returns a string[], like so:

    Enum.GetNames(typeof(DataSourceTypes))
    

    If you want to create a method that does only this for only one type of enum, and also converts that array to a List, you can write something like this:

    public List<string> GetDataSourceTypes()
    {
        return Enum.GetNames(typeof(DataSourceTypes)).ToList();
    }
    

    You will need Using System.Linq; at the top of your class to use .ToList()


    If you only need a single item in the list:

    string enumItemAsString = nameof(DataSourceTypes.Grid)