0 day streak
csharp / expert
Snippet

Bitwise Permission Masking for Access Control

For high-performance security systems, using bitwise operations on enums with the [Flags] attribute allows for extremely fast permission checking and memory-efficient storage of complex access rights.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[Flags]
enum Permissions : uint {
None = 0,
Read = 1 << 0,
Write = 1 << 1,
Delete = 1 << 2,
Admin = Read | Write | Delete
}
public static class SecurityManager {
public static bool HasAccess(Permissions userPerms, Permissions required) =>
(userPerms & required) == required;
public static Permissions Revoke(Permissions current, Permissions toRemove) =>
current & ~toRemove;
}
Breakdown
1
1 << 1
Uses the left-shift operator to assign unique bit positions to each permission level.
2
current & ~toRemove
Combines bitwise AND with bitwise NOT (complement) to surgically remove specific bits from the mask.