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
Release: 2025-01-17 09:47:11
Original
871 people have browsed it

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
}
Copy after login

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>();
Copy after login

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>();
    }
}
Copy after login

Usage:

var values = EnumUtil.GetValues<Foos>();
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template