You can use bitwise operations to combine different values into just one.
To add a value, use the OR :
var rgb = Cores.Vermelho | Cores.Verde | Cores.Azul;
To check if a value is present, use the AND operator (see method HasFlag
below):
if ((rgb & Cores.Azul) == Cores.Azul)
To remove a value use the NOT operator:
rgb &= ~Cores.Azul;
Enum.HasFlag *
If you are using .NET 4 or higher you can use the HasFlag method to check whether the value of the last enum is in the combination:
if (rgb.HasFlag(Cores.Azul))
Beware of no multiple of two
As you may have noticed, the combination is done with the bits of each combined value.
That is, if any of the values are not a multiple of two you may be combining several flags at once.
Example:
public enum Cores
{
Vermelho = 1, // Cor primária.
Verde = 2, // Cor primária.
Amarelo = 3, // Cor segundária. Mistura de vermelho com verde (1 & 2).
Azul = 4, // Cor primária.
Magenta = 5, // Cor segundária. Mistura de vermelho e azul (1 & 4).
Ciano = 6 // Cor segundária. Mistura de verde e azul (2 & 4).
}
var cores = Cores.Ciano | Cores.Magenta | Cores.Amarelo;
The variable cores
will have not only the flags Ciano
, Magenta
and Amarelo
but also will have Vermelho
, Verde
and Azul
:
cores.HasFlag(Cores.Vermelho); // True
cores.HasFlag(Cores.Verde); // True
cores.HasFlag(Cores.Azul); // True
But ... and the Flags attribute anyway?
Please note that we are not talking about the Flags attribute so far. Everything that has been said so far works without the enum being marked with the attribute.
The difference between an enum marked with Flags
and an unmarked one is:
- It changes the behavior of certain methods such as Format and ToString .
- It is especially useful in languages other than C #, such as VB, that do not support bitwise operations at language level .
-
-
-
-
Although the documentation makes explicit that the HasFlag method only works with enums marked with FlagsAttribute , according to my tests it worked normally with an enum Unmarked. Anyway follow the excerpt:
The HasFlag method is designed to be used with enumeration types that are marked with the FlagsAttribute attribute and can be used to determine whether multiple bit fields are set. For enumeration types that are not marked with the FlagsAttribute attribute, call either the Equals method or the CompareTo method.