0
0
C Sharp (C#)programming~3 mins

Why Flags attribute and bitwise enums in C Sharp (C#)? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could track many settings with just one variable and simple checks?

The Scenario

Imagine you want to track multiple settings for a user, like if they have notifications enabled, dark mode on, and location access granted. Without bitwise enums, you'd need separate variables for each setting, making your code bulky and hard to manage.

The Problem

Using separate variables for each option means writing lots of repetitive code to check or change settings. It's easy to forget to update one, causing bugs. Also, storing many booleans wastes memory and slows down your program when you want to check multiple settings at once.

The Solution

The Flags attribute with bitwise enums lets you combine multiple options into a single variable using bits. This means you can store many settings compactly and check or change them quickly with simple bit operations, making your code cleaner and faster.

Before vs After
Before
bool notifications = true;
bool darkMode = false;
bool locationAccess = true;

if (notifications && locationAccess) { /* do something */ }
After
[Flags]
enum UserSettings { None = 0, Notifications = 1, DarkMode = 2, LocationAccess = 4 }

UserSettings settings = UserSettings.Notifications | UserSettings.LocationAccess;

if ((settings & UserSettings.Notifications) != 0) { /* do something */ }
What It Enables

You can efficiently combine and manage multiple options in one variable, making your programs simpler, faster, and easier to maintain.

Real Life Example

Think of a music app where a song can be marked as favorite, downloaded, and shared. Using bitwise enums with Flags, the app can store all these states in one variable and quickly check or update them without juggling many separate flags.

Key Takeaways

Manual tracking of multiple options with separate variables is slow and error-prone.

Flags attribute with bitwise enums packs many options into one variable using bits.

This approach simplifies code, improves performance, and reduces bugs.