Listing Values

I have an enum class like

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

in my business object, I simply declare this listing as

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

and in the get / set method I tried as

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

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

+4
source share
5 answers

You can use this to get all the individual enumeration values:

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

If you do this more often, you can create a general 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)); } 
+12
source

GetValues returns System.Array , but we know that it is really TEnum[] (this is a one-dimensional array indexed from scratch), where TEnum is USERTYPE in your case. Therefore use:

 var allUsertypeValues = (USERTYPE[])Enum.GetValues(typeof(USERTYPE)); 
+3
source

You have basically a list of listings. Not individual elements within this listing.

To get a list of enumeration values, you can do

 string[] str = Enum.GetNames(typeof(USERTYPE)); 

For use in get / set, returns the string [] instead of List <>

 public string[] UserType { get { return Enum.GetNames(typeof(USERTYPE)); } } 

I think the set will not work here because you cannot add values ​​to the enumeration at runtime.

+2
source

If you want to get a specific enumeration value from the user.UserType list, you first need to specify the Add enum value in this list:

 var user = new User(); //1 value - PERMANENT user.UserType.Add(USERTYPE.Permanent); 

But if you only need to get all possible values ​​from an arbitrary enum , then you can try Enum.GetValues

 //2 values - Permanant and Temporary var enums = Enum.GetValues(typeof(USERTYPE)); 
+2
source

UserTypeCan, please try with this,

  UserType = Enum.GetValues(typeof(USERTYPE)).OfType<USERTYPE>().ToList(); 
+2
source

All Articles