C# › Enums & Flags

How would you write an extension method to safely add or remove a specific flag from a [Flags] enum value without manual bitwise operators scattered throughout your code?

Advanced

Answer

Define generic (or type-specific) extension methods that encapsulate the bitwise OR (for adding) and AND-with-complement (for removing) operations, giving calling code a clean, readable API instead of repeating raw bitwise expressions everywhere.
public static class PermissionsExtensions {
  public static Permissions AddFlag(this Permissions value, Permissions flag) => value | flag;
  public static Permissions RemoveFlag(this Permissions value, Permissions flag) => value & ~flag;
}

var perms = Permissions.Read;
perms = perms.AddFlag(Permissions.Write);      // Read, Write
perms = perms.RemoveFlag(Permissions.Read);    // Write
Real-world example Providing a clean, discoverable API for manipulating a permissions or feature-flags enum throughout a large codebase.

Common follow-ups: Could this same pattern be made generic to work with ANY [Flags] enum type, not just Permissions specifically?