Sobes.tech
Junior — Middle

In what situations is it better to use an enumeration type with flags for bitwise combinations?

sobes.tech AI

Answer from AI

Flag enumerations (bit flags) in C# are used to represent a set of boolean options or states that can be combined together. This approach is useful when you need to store multiple independent flags in a single number.

Use cases:

  • When you need to efficiently store and transmit multiple logical flags.
  • When different combinations of states are possible, and you need to quickly check for the presence of a specific flag using bitwise operations.
  • For configuring parameters, such as operating modes, access rights, or configuration options.

Example:

[Flags]
enum FileAccess {
    Read = 1,       // 0001
    Write = 2,      // 0010
    Execute = 4,    // 0100
    Delete = 8      // 1000
}

FileAccess permissions = FileAccess.Read | FileAccess.Write;

bool canWrite = (permissions & FileAccess.Write) == FileAccess.Write; // true

Here, access rights can be combined and checked using bitwise operations. This approach saves memory and simplifies logic when working with multiple options.