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

How Can I Iterate Through Enum Values in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-17 09:37:38566browse

How Can I Iterate Through Enum Values in C#?

Iterating over enumeration values ​​in C#

Declaring an enumeration in C# allows you to define a set of named constants. Iterating over these values ​​can be useful in a variety of situations.

To iterate over enumeration values, you can utilize the Enum.GetValues method. Consider the following Foos enumeration:

<code class="language-csharp">public enum Foos
{
    A,
    B,
    C
}</code>

Using Enum.GetValues you can retrieve an array of enumeration values ​​like this:

<code class="language-csharp">var values = Enum.GetValues(typeof(Foos));</code>

Alternatively, for the typed version, you can use:

<code class="language-csharp">var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();</code>

To simplify this process, you can implement a helper function, for example:

<code class="language-csharp">public static class EnumUtil
{
    public static IEnumerable<T> GetValues<T>()
    {
        return Enum.GetValues(typeof(T)).Cast<T>();
    }
}</code>

Using this helper function, you can iterate over enumeration values ​​using:

<code class="language-csharp">var values = EnumUtil.GetValues<Foos>();</code>

The above is the detailed content of How Can I Iterate Through 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