Enumerating Enum Values in C#
Looping through all possible values of an enum is a common requirement in C# programming. Here's how you can achieve it:
Using Enum.GetValues Method
The Enum.GetValues method returns an array of all values in the specified enum type. You can use this array to loop through the values using a foreach loop. For example:
public enum Foos { A, B, C } var values = Enum.GetValues(typeof(Foos)); foreach (var value in values) { // Do something with the value }
Using the Typed Enum.GetValues Method
The Enum.GetValues method also has a typed version that returns an array of the specified enum type. This version is more convenient to use when you know the enum type at compile time. For example:
var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();
Using a Helper Class
To simplify the process of getting enum values, you can create a helper class that provides a generic method for retrieving values:
public static class EnumUtil { public static IEnumerable<T> GetValues<T>() { return Enum.GetValues(typeof(T)).Cast<T>(); } }
Usage:
var values = EnumUtil.GetValues<Foos>();
The above is the detailed content of How Can I Iterate Through All Enum Values in C#?. For more information, please follow other related articles on the PHP Chinese website!