4

How this enum is assigned? What are all the value for each?

public enum SiteRoles
{
    User = 1 << 0,
    Admin = 1 << 1,
    Helpdesk = 1 << 2
}

What is the use of assigning like this?

Used in this post

Soner Gönül
  • 94,086
  • 102
  • 195
  • 339
Billa
  • 5,028
  • 22
  • 58
  • 103

1 Answers1

10

They're making a bit flag. Instead of writing the values as 1, 2, 4, 8, 16, etc., they left shift the 1 value to multiply it by 2. One could argue that it's easier to read.

It allows bitwise operations on the enum value.

1 << 0 = 1 (binary 0001)
1 << 1 = 2 (binary 0010)
1 << 2 = 4 (binary 0100)
dee-see
  • 22,825
  • 5
  • 58
  • 88