Daily Knowledge Drop
The static Enum.GetValues
method value be used to get an array of the enum values, which can be output as a string or corresponding compatible underlying value
Enum.GetValues
The function and usage of Enum.GetValues
is very simple - it converts an enum into an array of the enum values.
Consider the following enum:
public enum OrderStatus
{
New = 0,
Processing = 1,
Fulfilled = 2,
OutOnDelivery = 3,
Delivered = 4
}
This can be converted to an array as follows:
OrderStatus[] enumItems = Enum.GetValues<OrderStatus>();
This array can now be iterated over, and output either as a string or compatible underlying type:
foreach (var item in Enum.GetValues<OrderStatus>())
{
// output the string value
Console.WriteLine(item);
// output the underlying value
Console.WriteLine((int)item);
// this would also work
//Console.WriteLine((double)item);
}
The output of the above is:
New
0
Processing
1
Fulfilled
2
OutOnDelivery
3
Delivered
4
Simple, easy and very useful.
Notes
A small but useful piece of knowledge for today. This can be leveraged to automatically populate a UI dropdown with available options, for example, instead of having multiple places with a list of possible values.
References
How to Enumerate an Enum in C#
Daily Drop 220: 12-12-2022
At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.
The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.On This Page