Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an array of all enum values in C#?

Tags:

c#

enums

I have an enum that I'd like to display all possible values of. Is there a way to get an array or list of all the possible values of the enum instead of manually creating such a list? e.g. If I have an enum:

public enum Enumnum { TypeA, TypeB, TypeC, TypeD }

how would I be able to get a List<Enumnum> that contains { TypeA, TypeB, TypeC, TypeD }?

like image 368
Mark LeMoine Avatar asked Sep 28 '10 20:09

Mark LeMoine


People also ask

How do I get a list of all enum values?

The idea is to use the Enum. GetValues() method to get an array of the enum constants' values. To get an IEnumerable<T> of all the values in the enum, call Cast<T>() on the array. To get a list, call ToList() after casting.

Can you put enums in 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.


4 Answers

This gets you a plain array of the enum values using Enum.GetValues:

var valuesAsArray = Enum.GetValues(typeof(Enumnum)); 

And this gets you a generic list:

var valuesAsList = Enum.GetValues(typeof(Enumnum)).Cast<Enumnum>().ToList(); 
like image 70
Dirk Vollmar Avatar answered Oct 19 '22 00:10

Dirk Vollmar


Try this code:

Enum.GetNames(typeof(Enumnum)); 

This return a string[] with all the enum names of the chosen enum.

like image 30
Øyvind Bråthen Avatar answered Oct 19 '22 01:10

Øyvind Bråthen


Enum.GetValues(typeof(Enumnum));

returns an array of the values in the Enum.

like image 32
duraz0rz Avatar answered Oct 19 '22 01:10

duraz0rz


You may want to do like this:

public enum Enumnum { 
            TypeA = 11,
            TypeB = 22,
            TypeC = 33,
            TypeD = 44
        }

All int values of this enum is 11,22,33,44.

You can get these values by this:

var enumsValues = Enum.GetValues(typeof(Enumnum)).Cast<Enumnum>().ToList().Select(e => (int)e);

string.Join(",", enumsValues) is 11,22,33,44.

like image 28
Ali Soltani Avatar answered Oct 19 '22 01:10

Ali Soltani