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
Release: 2025-01-17 09:37:38
Original
565 people have browsed it

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

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

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

Alternatively, for the typed version, you can use:

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

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

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

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

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!

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