An Enum with this attribute allows you to put multiple values into a single variable. For example:
var atributosDoArquivo = FileAttributes.ReadOnly | FileAttributes.Hidden;
The Enum marked with the attribute [Flags]
works by doing operations bitwise, i.e., in a simpler example:
[Flags]
public enum MeuEnum
{
Um = 1 << 0, // 1
Dois = 1 << 1, // 2
Tres = 1 << 2, // 4
}
* No problem using the operator <<
, because in this case the values are solved at compile time.
Note that for the correct operation you need to put the bit in the correct position, because:
// valores do enum
Um = 00000001
Dois = 00000010
Tres = 00000100
So when we assign two values of this Enum to a variable, the result will be:
var resultado = MeuEnum.Um | MeuEnum.Tres; // 00000101
Both the bit of Um
and Tres
are present in the result, so this variable contains the two values.
If your variable has more than one value and you want to know if it contains only one value, you should not compare the variable directly as you may have thought to do, because if it contains more than one value your condition will fail.
To find out if resultado
has Um
and any other value, compare this way:
if ((resultado & MeuEnum.Um) == MeuEnum.Um)
For
// resultado & MeuEnum.Um == MeuEnum.Um
(00000101 & 00000001) = 00000001
If you want to remove only one value while keeping all others, you can use:
resultado &= ~MeuEnum.Um;
For
// resultado & inverso de Um = Tres
00000101 & 11111110 = 00000100
More about C# operators on MSDN.
This link does not answer anything, but it is about a question I asked regarding the use of
[Flags]
, It is at complement level (: http://answall.com/questions/12835/howto show correct name-em-um-enum-bitwise– anisanwesley