Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use FlagsAttribute

Tags:

c#

enums

A developer on my project has implemented the following enum

[Flags]
public enum Permissions
{
    Overview = 1,
    Detail = 3,
    Edit = 7,
    Delete = 31,
    Block = 39, // Requires Edit = 7, and It's own location = 32. Therefore 7 + 32 = 39.
    Unblock =  71, // Requires Edit = 7, and It's own location = 64. Therefore 7 + 64 = 71.
    All = int.MaxValue
}

Now, as you can see he has, for example, made Details = 3. The reason he has done this is that Details (which should have been 2) includes overview as well (2+1=3).

I always thought that the way to do these things is to use powers of 2 in the enum and do any oring and anding outside of the enum. What's going on here?

like image 443
Sachin Kainth Avatar asked Dec 21 '22 07:12

Sachin Kainth


1 Answers

There's nothing wrong with defining combinations in the enum in order to make life easier for users of the enum. That said, it is probably a short-sighted decision (inflexible and hard to understand code) decision to leave out that various power-of-2 options that make up the combinations.

like image 152
Robert Levy Avatar answered Jan 06 '23 11:01

Robert Levy