Junior — Middle
Can you explain what using flags inside enumerations (Enum) means?
sobes.tech AI
Answer from AI
In C#, using flags within enumerations (Enum) means that each enumeration value represents a separate bit, and they can be combined using bitwise operations (e.g., OR, AND). This is usually done with the [Flags] attribute, which indicates that the enumeration is intended to store a set of flags.
This allows for convenient storage and checking of multiple states or options simultaneously.
Example:
[Flags]
enum FileAccess
{
Read = 1, // 0001
Write = 2, // 0010
Execute = 4, // 0100
ReadWrite = Read | Write // 0011
}
// Usage:
FileAccess access = FileAccess.Read | FileAccess.Write;
bool canRead = (access & FileAccess.Read) == FileAccess.Read; // true
bool canExecute = (access & FileAccess.Execute) == FileAccess.Execute; // false
Thus, flags allow combining values and checking for the presence of specific options in an enumeration variable.