Search code examples
c#.netenumsenum-flags

How to check which enum values are set based on a combined value


I am having 5 checkboxes.

public enum animals : int
{
    Cat      = 1
    ,Dog     = 2
    ,Mouse   = 3
    ,Rat     = 4
    ,Lizzard = 5
}

On saving my window I can sum up they checkboxes that are checked, in int res_flags and save it.

int res_flags = 0;

if ((bool)this.chbCat.IsChecked)        res_flags |= (int)animals.Cat;
if ((bool)this.chbDog.IsChecked)        res_flags |= (int)animals.Dog;
if ((bool)this.chbMouse.IsChecked)      res_flags |= (int)animals.Mouse;
if ((bool)this.chbRat.IsChecked)        res_flags |= (int)animals.Rat;
if ((bool)this.chbLizzard.IsChecked)    res_flags |= (int)animals.Lizzard;

How can I check at the start which were checked based on the int res_flags?


Solution

  • How can I check at the start which were checked based on the int res_flags?

    In this case it is very convenient to add the [Flags] attribute to the enum, and make the values powers of 2. It's easy to make sure the values are powers of 2 by using bit-shift operator<< with an increasing value.

    Then you can use Enum.HasFlag to check if a specific flag is set:

    [Flags]
    public enum animals : int
    {
        Cat = 1 << 0,
        Dog = 1 << 1,
        Mouse = 1 << 2,
        Rat = 1 << 3,
        Lizzard = 1 << 4
    }
    
    static void Main(string[] args)
    {
        animals res_flags = animals.Cat | animals.Dog;
    
        Console.WriteLine(res_flags.HasFlag(animals.Cat));
        Console.WriteLine(res_flags.HasFlag(animals.Dog));
        Console.WriteLine(res_flags.HasFlag(animals.Mouse));
        Console.WriteLine(res_flags.HasFlag(animals.Rat));
        Console.WriteLine(res_flags.HasFlag(animals.Lizzard));
    }
    

    Output:

    True
    True
    False
    False
    False
    

    Live demo

    Note that res_flags is no longer of type int, but rather of the enum type animals.