introduction

Introduction

Enumerations (enums) in C# provide a convenient way to define a set of named values. However, there are scenarios where we must represent multiple values or combinations of values using a single enum variable. This is where bitwise enums come into play. Bitwise enums in C# allow for efficient and flexible flag-based enumerations, enabling us to store and manipulate multiple values in a compact form. In this article, we will delve into the concept of bitwise enums and explore how to use them effectively in C#.

What is Bitwise Enums?

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.

How do we define 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,

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

C#

Copy

In the above code, we define a DaysOfWeek enum where each day of the week is assigned a unique power of 2. The None value is assigned 0, indicating no days are selected.

Combining Bitwise Enums

Ebook Download
View all
Learn
View all