How does the [Flags] attribute change the output of ToString() on a combined flags enum value?
Short answer
Without [Flags], calling ToString() on a value that doesn't exactly match any single named member just returns the raw numeric value as a string; WITH [Flags], the runtime recognizes the value as a combination and formats it as a comma-separated list of the individual flag names…
Advertisement
AModel answer
Without [Flags], calling ToString() on a value that doesn't exactly match any single named member just returns the raw numeric value as a string; WITH [Flags], the runtime recognizes the value as a combination and formats it as a comma-separated list of the individual flag names that make it up.
[Flags]
public enum Permissions { None = 0, Read = 1, Write = 2, Delete = 4 }
var combined = Permissions.Read | Permissions.Write;
Console.WriteLine(combined.ToString()); // "Read, Write" -- thanks to [Flags]
// Without [Flags], the same combined value would just print "3"Real-world example
Displaying a human-readable summary of a user's combined permissions in a log message or admin dashboard.
Likely follow-ups
- How would you use HasFlag() as an alternative, more readable way to check for a specific flag's presence?
Related topics