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 }
?
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.
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.
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();
Try this code:
Enum.GetNames(typeof(Enumnum));
This return a string[]
with all the enum names of the chosen enum.
Enum.GetValues(typeof(Enumnum));
returns an array of the values in the Enum.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With