There are ready-made enums

[Flags] public enum UserFlags { guest = 0, // GUEST USER // normal = 1, // NORMAL USER (DEFAULT) // banned = 2, // USER IS BLOCKED // online = 4 // USER IS ONLINE // } 

This is how I set the flags:

 user.Flags = UserData.UserFlags.normal; user.SetFlag(UserData.UserFlags.guest); user.SetFlag(UserData.UserFlags.online); public UserFlags Flags { get; internal set; } public void SetFlag(UserFlags flag, bool state = true) { Flags = state ? Flags |= flag : Flags &= ~flag; } 

But if I try to display Flags as a test, only Online and Normal returns to the console, but the guest is not taken into account. Why?

  • Are you sure this is C? ... - Harry
  • @Harry sorry corrected - Kostya

2 answers 2

The problem is that with the guest flag you are trying to operate with a nonexistent 0th bit. The solution is quite simple - start from the 1st bit:

 [Flags] public enum UserFlags { guest = 1, // GUEST USER // normal = 2, // NORMAL USER (DEFAULT) // banned = 4, // USER IS BLOCKED // online = 8 // USER IS ONLINE // } 

Another option is to use a bit shift, so as not to be confused by the values ​​when there are a lot of flags and they become quite large numbers:

 [Flags] public enum UserFlags { guest = 1 << 0, // GUEST USER // normal = 1 << 1, // NORMAL USER (DEFAULT) // banned = 1 << 2, // USER IS BLOCKED // online = 1 << 3 // USER IS ONLINE // } 

    ToString() does not handle enum with a value of 0 and does not output to the console