Home >Backend Development >C++ >How Can I Iterate Through All Enum Values in C#?

How Can I Iterate Through All Enum Values in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-17 09:47:11872browse

How Can I Iterate Through All Enum Values in C#?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn