Nave Tseva
Nave Tseva

Reputation: 401

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?

Upvotes: 1

Views: 1374

Answers (2)

Matthieu
Matthieu

Reputation: 4620

You can use the flags attribute in C++/CLI like this:

[System::Flags]
public enum class Days : int
{
    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. But it can be required by some static code analysis tools:

PVS Studio

Sonar Lint

Upvotes: 1

mm8
mm8

Reputation: 169390

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#?

Upvotes: 1

Related Questions