C# › Enums & Flags

What is the performance consideration when using Enum.HasFlag() versus a direct bitwise AND check?

Intermediate

Answer

Enum.HasFlag() involves BOXING the enum value (converting it to an object) internally in older .NET versions, making it measurably slower than a direct bitwise AND comparison in performance-sensitive, high-frequency code — modern .NET has optimized this significantly, but the direct bitwise check remains marginally faster and avoids any boxing concern entirely.
[Flags]
public enum Permissions { None = 0, Read = 1, Write = 2 }
var perms = Permissions.Read;

// Slightly slower historically (boxing), but more readable
bool hasRead1 = perms.HasFlag(Permissions.Read);

// Faster, no boxing, less readable
bool hasRead2 = (perms & Permissions.Read) == Permissions.Read;
Real-world example Choosing the direct bitwise check over HasFlag() specifically in a tight, performance-critical loop checking permissions millions of times.

Common follow-ups: At what call frequency does this performance difference actually become practically noticeable in a real application?