Enum - Working with [Flags]
A nice feature of the language is the ability to tag an enum with the [Flags] attribute.
Such tagging makes the use of the enum in a bitwise manner, you can choose multiple values to an enum field.
Working with such enum tagged with flags introduces a different approach than working against a normal enum.
Let's assume we define the following enum:
[
Flags]
public enum Day
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
Tip: An "All" item could be added to the list of items in the enumeration as follows: All = Sunday | Monday | Tuesday |.. So On
Imagine the purpose would be writing an alerter service which invokes a certain operation on a pre-defined day.
There can be multiple days chosen so this enum answers this requirement.
The first value should be 1, then just double the value for each consecutive item.
Here's how you work against such an enum:
Declaration: (Same as normal enum)
Day day = Day.Sunday;
Day day = Day.Sunday | Day.Monday (sets the day to contain both Sunday and Monday)
Adding a Day::
day |= Day.Tuesday;
Removing a Day:
day ^= Day.Tuesday:
Checking if the field contains a day value:
bool contains = (day & Day.Tuesday == Day.Tuesday); (checks if day contains Tuesday)
A little bonus - checking if the field contains a 'DayOfWeek' (.Net enum type, non flags):
bool contains = (day & (Day)Math.Pow(2, (double)DayOfWeek.Tuesday) == Day.Tuesday); (checks if day contains DayOfWeek.Tuesday)