Bitwise Enumeration

A bitwise enum is an enum type that uses bitwise operations to combine multiple enum values into a single value.
Each enum value is assigned a unique bit flag, represented by a power of 2.
By assigning these flags, we can represent multiple enum values by combining or masking them using bitwise operators.

Defining Bitwise Enums

To define a bitwise enum, we need to decorate it with the [Flags] attribute, indicating that the enum values can be combined using bitwise operations. Here's an example,
The DaysOfWeek enum has every day of the week assigned a unique power of 2.
The None value is assigned 0, indicating no days are selected.

[Flags] enum DaysOfWeek { 
    None = 0,
    Monday = 1,
    Tuesday = 2,
    Wednesday = 4,
    Thursday = 8,
    Friday = 16,
    Saturday = 32,
    Sunday = 64

Combining Bitwise Enums

To combine the Monday, Wednesday, and Friday enum values we use the bitwise OR (|) operator.

DaysOfWeek selectedDays = DaysOfWeek.Monday | DaysOfWeek.Wednesday | DaysOfWeek.Friday 

Checking for Enum Values

To check if the Monday value is set in the selectedDays variable we use the bitwise AND (&) operator.

if ((selectedDays & DaysOfWeek.Monday) != 0) { 
  Console.WriteLine("Monday is selected.");

Removing Enum Values

To remove the Wednesday specific enum value from the set in the selectedDays variable, we use the bitwise XOR (^) operator.

selectedDays ^= DaysOfWeek.Wednesday; 

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext