Read the syntax
A Flags enum represents a set of independent options using nonoverlapping bits. Bitwise operators combine, test and clear those options. Use a .NET 8+ console project; replace Program.cs with this C# example.
The bitwise OR sets both bits. AND with the complement of Write clears only that bit, leaving Read enabled.
Syntax
[Flags] enum Options { None = 0, Read = 1, Write = 2 }Examples
Combining Flags Enums
Use a .NET 8+ console project; replace Program.cs with this C# example.
using System;
Access rights = Access.Read | Access.Write;
Console.WriteLine(rights.HasFlag(Access.Read));
rights &= ~Access.Write;
Console.WriteLine(rights);
[Flags]
enum Access { None = 0, Read = 1, Write = 2, Export = 4 }- Expected output: True Read
- The bitwise OR sets both bits. AND with the complement of Write clears only that bit, leaving Read enabled.
- Assign powers of two to independent flags and define None as zero.
Best practices
- Assign powers of two to independent flags and define None as zero.
- Validate unknown bits when reading enum values from external input.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference