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?
Short 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.
Advertisement
AModel 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); // WriteReal-world example
Providing a clean, discoverable API for manipulating a permissions or feature-flags enum throughout a large codebase.
Likely follow-ups
- Could this same pattern be made generic to work with ANY [Flags] enum type, not just Permissions specifically?
Related topics