0 votes
by (2.5k points)

I want to list all values of an enum in a drop downlist, but I'm not sure how to get each value other than hardcoding each one in the list. 

Also things like : 

enum Colors
{
	Red, 
	Green, 
	Blue
}

foreach(var color in Colors)
{

}

Just gives me the error : 

'Colors' is a type, which is not valid in the given context   

1 Answer

0 votes
by (2.5k points)

In later versions of .NET Core/.NET, you can use the generic version of Enum.GetValues like so : 

var colorList = Enum.GetValues<Colors>(); //Returns an array of Color values

However in earlier versions you needed to cast the result like so : 

var colorList = Enum.GetValues(typeof(Colors)).Cast<Colors>();

Either way, the static Enum helpers are the best way of getting all the possible values of an enum into a list. 

Welcome to .NET Q&A, where you can ask questions and receive answers from other members of the community.
...