Search code examples
c#enumsattributesclrenum-flags

CLR - Declare enum with "Flags" attribute


I have the following Enum in CLR / CLI:

public enum class Days
{
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
};

In C#, if I wanted to create a combination of the selected enums, I used to add [Flags] attribute before the declaration of the enum.

Does anything similar to that exist in C++ CLR?


Solution

  • The FlagsAttribute in C# just indicates that the enumeration can be treated as a bit field.

    What really matters is that you define the enumeration values appropriately so that AND, OR, NOT and XOR bitwise operations can be performed on them, i.e. you should assign each enumeration value the next greater power of 2:

    public enum class Days
    {
        Sunday = 1,
        Monday = 2,
        Tuesday = 4,
        Wednesday = 8,
        Thursday = 16,
        Friday = 32,
        Saturday = 64
    };
    

    [Flags] does not automatically make the enum values powers of two.

    What does the [Flags] Enum Attribute mean in C#?