Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum values in a list

Tags:

c#

asp.net

I've a enum class like,

public enum USERTYPE
{
   Permanant=1,
   Temporary=2,
}

in my business object I just declare this enum as

private List<USERTYPE> userType=new List<USERTYPE>;

and in the get/set method, I tried like

public List<USERTYPE> UserType
    {
        get 
        {
            return userType;
        }
        set
        { 
            userType= value; 
        }
    }

here it returns the no of rows as 0, how can I get all the values in the Enum here, can anyone help me here...

like image 601
shanish Avatar asked Jun 28 '12 07:06

shanish


People also ask

Can enum be a list?

Enum to List. An enum type internally contains an enumerator list. Whenever there is a situation that you have a number of constants that are logically related to each other, then it is the best way that you can group together these constants in an enumeration.

How do you iterate over an enum?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.

Can an enum be an array?

Enums are value types (usually Int32). Like any integer value, you can access an array with their values. Enum values are ordered starting with zero, based on their textual order. MessageType We see the MessageType enum, which is a series of int values you can access with strongly-typed named constants.


1 Answers

You can use this to get all individual enum values:

private List<USERTYPE> userTypes = Enum.GetValues(typeof(USERTYPE)).Cast<USERTYPE>().ToList();

If you do things like this more often, you could create a generic utility method for it:

public static T[] GetEnumValues<T>() where T : struct {
    if (!typeof(T).IsEnum) {
        throw new ArgumentException("GetValues<T> can only be called for types derived from System.Enum", "T");
    }
    return (T[])Enum.GetValues(typeof(T));
}
like image 107
Botz3000 Avatar answered Sep 23 '22 19:09

Botz3000