I am trying to have a method which fills a list based on the flags set in the enum. My problem is that the iteration through the enum iterates over all elements and not only the elements with one bit set:
using System;
using System.Collections.Generic;
public class Program
{
[Flags]
public enum Modes
{
A = 1 << 0,
B = 1 << 1,
C = 1 << 2,
AC = A | C,
All = ~0
}
public class Type
{
public Type(Modes mode){}
}
public static List<Type> Create(Modes modesToCreate = Modes.All)
{
var list = new List<Type>();
foreach(Modes mode in Enum.GetValues(typeof(Modes)))
{
if(modesToCreate.HasFlag(mode))
{
Console.WriteLine(mode);
list.Add(new Type(mode));
}
}
Console.WriteLine();
return list;
}
public static void Main()
{
Create();
Create(Modes.A | Modes.C);
}
}
Real output:
A
B
C
AC
All
A
C
AC
Desired Output:
A
B
C
A
C
How can I ignore the combined flags on the iteration or only iterate over the single bit enum values?