How to create a bit-based enumeration
C#, C# Language February 24th, 2006If you want to create an enumeration that acts like a set, where the value of the enumeration can be a combination of any of the members of the enumeration then you C# allows you to do this using the FlagsAttribute.
Simply add the attribute to the start of the enumeration and the enumeration values will be treated as bit flags instead.
[csharp]
[FlagsAttribute]
enum Colors : short
{
None = 0,
Red = 1,
Green = 2,
Blue = 4,
White = 7
};[/csharp]
You can use bitwise operators Not, And, Or and XOR on the enumeration.
e.g. to see if an enumeration value is set
[csharp]
if ( Colors & Red == Red)
{
// do something
}
[/csharp]
Note that the not (!) does not work on bitwise operations so the complement(~) operator is required.
So to remove a the red and green flag from the set…
[csharp]
Colors = Colors & ~(Red | Green);
[/csharp]
Recent Comments