Home >Backend Development >C++ >How to Iterate Over Only the Set Flags in a C# Enum?

How to Iterate Over Only the Set Flags in a C# Enum?

DDD
DDDOriginal
2024-12-26 21:53:13488browse

How to Iterate Over Only the Set Flags in a C# Enum?

Iterating Over Values of an Enum with Flags

Question:

When working with an enum that supports flags, how can one iterate specifically over the individual, single-bit values that are set in a particular variable? Is it possible to avoid iterating over the entire enum using Enum.GetValues?

Answer:

Yes, it's possible to iterate over the individual flag values in an enum variable without the need to enumerate the entire enum and check if the values are set. This can be achieved using the following code snippet:

static IEnumerable<Enum> GetFlags(Enum input)
{
    foreach (Enum value in Enum.GetValues(input.GetType()))
        if (input.HasFlag(value))
            yield return value;
}

Explanation:

  1. The GetValues method returns an array of all possible values for the specified enum type.
  2. For each value in the array, the HasFlag method is used to check if the flag is set in the input variable.
  3. If the flag is set, the value is yielded back from the GetFlags method.

By using this approach, you can efficiently iterate over the individual flag values of the enum variable.

The above is the detailed content of How to Iterate Over Only the Set Flags in a C# Enum?. 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