How to use enum flags in C#
By FoxLearn 3/4/2025 9:51:23 AM 68
For example:
FilePermissions permissions = FilePermissions.Read | FilePermissions.Write;
In this article, I’ll show how to create and use enum flags.
Use [Flags] attribute on enum type
To enable an enum to hold multiple values:
Add the
[Flags]
attribute to the enum type.Assign integer values as powers of 2.
Optionally include
None = 0
to represent no values set.
For example:
[Flags] public enum FilePermissions { None = 0, Read = 1, Write = 2, Execute = 4, Delete = 8 }
This example represents different file permissions. The reason values are powers of 2 is that they correspond to bit positions in binary representation:
[Flags] public enum FilePermissions { None = 0b0000, // 0 Read = 0b0001, // 1 Write = 0b0010, // 2 Execute = 0b0100, // 4 Delete = 0b1000 // 8 }
Since each value corresponds to a bit position, bitwise ORing them together allows multiple values to be stored in a single variable. For example, FilePermissions.Read | FilePermissions.Write
results in the following binary operation:
0001 (Read) | 0010 (Write) ----- 0011 (Read & Write)
Use HasFlag() to check if a value is set
To check if an enum contains a specific value, use HasFlag()
:
FilePermissions permissions = FilePermissions.Read | FilePermissions.Write; if (permissions.HasFlag(FilePermissions.Read)) { Console.WriteLine("Has Read permission!"); } if (permissions.HasFlag(FilePermissions.Write)) { Console.WriteLine("Has Write permission!"); }
Output:
Has Read permission! Has Write permission!
Alternatively, you can check using bitwise AND:
if ((permissions & FilePermissions.Read) == FilePermissions.Read) { Console.WriteLine("Has Read permission!"); }
You can add more values to the enum at any time using bitwise OR:
FilePermissions permissions = FilePermissions.Read | FilePermissions.Write; if (!permissions.HasFlag(FilePermissions.Execute)) { permissions |= FilePermissions.Execute; } Console.WriteLine(permissions.ToString());
Output:
Read, Write, Execute
Using enum flags simplifies working with multiple values, making code more readable and efficient.
- How to use JsonConverterFactory in C#
- How to serialize non-public properties using System.Text.Json
- The JSON value could not be converted to System.DateTime
- Try/finally with no catch block in C#
- Parsing a DateTime from a string in C#
- Async/Await with a Func delegate in C#
- How to batch read with Threading.ChannelReader in C#
- How to ignore JSON deserialization errors in C#