Need a simple CRM and Project Management system?
Check out JobNimbus - CRM for Contractors and Service Professionals.

C# Get Enum values as a List

Many times you have an enumeration that contains a list of items that you may want to display to the user or bind to a drop down list. For instance, let's say you had an enumeration that defined possible user roles in a simple user authentication system like this:

/// <summary>
/// List of roles a user can authenticate as.
/// </summary>
public enum UserRoleType
{
    Administrator,
    PowerUser,
    ViewOnly
}

If we wanted to add these fields to an ASP.NET DropDownList control, we might write some code like this:

ddlUserRole.Items.Add(UserRoleType.Administrator.ToString());
ddlUserRole.Items.Add(UserRoleType.PowerUser.ToString());
ddlUserRole.Items.Add(UserRoleType.ViewOnly.ToString());

There are a couple of problems here. If you ever change your enum to add, edit, or remove a value, you need to also change every place in the code where this value is referenced. If you add a new value to your enum, you may not remember to add it here and would see no compile error.

There is an easier way to get all values from an enumeration and write the code above. Here is a simple method that gets all values from an enum and returns them as a list of strings:

/// <summary>
/// Gets list of all enum values for the type specified as a list of strings.  
/// </summary>
/// <param name="enumType">The type of enum to iterate values from.</param>
public static List<string> GetEnumValues(Type enumType)
{
    List<string> itemList = new List<string>();

    var listOfValues = Enum.GetValues(enumType);
    foreach (var value in listOfValues)
    {
        itemList.Add(value.ToString());
    }

    return itemList;
}

So instead of writing code to handle each enum value, you can just loop them like this:

List<string> listOfValues = GetEnumValues(typeof(UserRoleType));
foreach (var value in listOfValues)
{
    ddlUserRole.Items.Add(value);
}

Now, no matter whether your added, edited, or deleted a value in your enum, you would not to change the above code.