Showing posts with label list of all enum values. Show all posts
Showing posts with label list of all enum values. Show all posts

Wednesday, June 6, 2012

Getting list of Enum in C#

Here is the code to get the list of all the Enum values in a Enum

public static List<T> GetEnumValues<T>()
        {
            var type = typeof(T);
            if (!type.IsEnum)
                throw new ArgumentException("Type '" + type.Name + "' is not an enum");

            return (
              from field in type.GetFields(BindingFlags.Public | BindingFlags.Static)
              where field.IsLiteral
              select (T)field.GetValue(null)
            ).ToList();
        }


Lets say you enum is like this

public enum CustomerType
{
        Master,
        Normal,
        Existing
}

To get the list that contains all the CustomerType like (Master,Normal,Existing)

You need to write code like this
GetEnumValues<CustomerType>() and you get the list of CustomerType enum values.

Your comments/questions/suggestions are appreciated.

Cheers!
Vinod