0

I define my roles like this:

[Flags]
public enum Roles : byte
{        
    View = 1,       
    Edit = 2,    
    Admin = (View | Edit)
}
  • View role, can view only
  • Edit can view and edit only
  • Admin can do Admin stuff, edit and view

Am I doing something wrong in defining my Enum?

user2818430
  • 5,853
  • 21
  • 82
  • 148

2 Answers2

2

That looks fine, though for flags you must remember you cannot increment by ones (1, 2, 3, 4) - it must be done like: 1, 2, 4, 8.

Using your enum definition:

[Flags]
public enum Roles : byte
{
    View = 1,
    Edit = 2,
    Admin = (View | Edit) // Good for code readability - and if the values change
}

You can see that you can detect individual flags set like this (even specifically the Admin one).

Roles role = Roles.Admin;
bool canView = ((role & Roles.View) == Roles.View);
bool canEdit = ((role & Roles.Edit) == Roles.Edit);
bool isAdmin = (role == Roles.Admin);

You can see this work: https://dotnetfiddle.net/0pm4jW

I also like this kind of definition for readability (and not having to calculate the math if I want to add one later).

[Flags]
public enum Roles : byte
{
    View   = 1 << 0, // 1
    Edit   = 1 << 1, // 2
    Delete = 1 << 2, // 4
    Share  = 1 << 3, // 8
    Admin = (View | Edit | Delete | Share)
}
Chris
  • 1,118
  • 8
  • 24
0

The admin definition is valid only in case you want to separate roles and use Admin to group them. Just rewrite your enum into english:

View is equal View and nothing more
Edit is equal Edit and nothing more
Admin is equal Admin or Edit or View

If you want roles fallback (like Admin -> Edit -> View) you have to consider it as unique roles (even admin) and use order to specify how the role is important:

public enum Roles // note there is no flag attribute
{        
    View = 1,       
    Edit = 2,    
    Admin = 3
}

how to test role? just create simple function:

bool isInRole(Roles currentRole, Roles expectedRole)
{
    return currentRole >= expectedRole;
}

isInRole(Roles.Admin, Roles.Admin); // true
isInRole(Roles.Edit, Roles.Admin); // false
isInRole(Roles.Edit, Roles.Edit); // true
isInRole(Roles.Edit, Roles.View); // true
Aik
  • 3,528
  • 3
  • 19
  • 20