Flags attribute for Enums

If you want to be able to use several of the enum options at once you can use the FLAGS attribute when declaring the enum.

[Flags]
public enum AccessRights : short
{
  READ = 1,
  WRITE = 2,
  EXECUTE = 4
}






To make it work you need to enumerate the fields in powers of two (1,2,4,8…). You should also avoid negative numbers. You can read more at Microsoft regarding what to think of when programming enums with Flags attribute.

To use multiple enum values

AccessRights access = AccessRights.READ | AccessRights.EXECUTE;

To add another enum value you need to use the | operator (+ is not valid).

access = access | AccessRights.WRITE;

But to remove an enum value you can use the – operator.

access -= AccessRights.READ;

Check if user has READ access

if ((access & AccessRights.READ) == AccessRights.READ)
{
  ...
}

Code examples for simple enums are available here.