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
  • 97,193
  • 102
  • 206
  • 364
Billa
  • 5,226
  • 23
  • 61
  • 105
  • Because the answers already explain it in better detail I leave this as a comment: `1 << X` is the same thing as doing `2^X` in math (where `^` is the power symbol not the XOR symbol) so you are assigning the values `2^0`, `2^1`, `2^2` – Scott Chamberlain Nov 27 '13 at 14:30
  • Often used in conjunction with `[Flags]` attribute, relevant http://stackoverflow.com/q/8447/841176 – Konstantin Nov 27 '13 at 14:32
  • More generally `X << Y` is equivalent to `X * Math.Pow(2,Y)`. This is extremely useful for creating large powers of 2 numbers. Say you wanted to create a 4K byte array for a buffer it would just be `new byte[4 << 10]` ( `x << 10` is `K`, `x << 20` is `M`, `x << 30` is `G`) – Scott Chamberlain Nov 27 '13 at 14:45

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
  • 23,668
  • 5
  • 58
  • 91
  • `bitshift operator` how do i understand this? I dont know how to read this statement `User = 1 << 0` and use it – Billa Nov 27 '13 at 14:27
  • LOL - it could certainly be easier to count if there are large enumerations. That's a neat trick, @Billa. I'll have to remember that one. –  Nov 27 '13 at 14:27
  • @Billa See MSDN reference on the `<<` operator http://msdn.microsoft.com/en-us/library/vstudio/a1sway8w.aspx Basically it shifts the binary representation of the number. binary 1 becomes binary 10. – dee-see Nov 27 '13 at 14:28
  • Bit shift operator. `1 << 0` is really `0001`. `1 << 1` is `0010`, etc. –  Nov 27 '13 at 14:28
  • 2
    `One could argue that it's easier to read` .. one could also argue that it wasn't :) – Jens Kloster Nov 27 '13 at 14:29
  • 3
    @JensKloster For sure, that's why I didn't go straight for a "it's easier to read" haha – dee-see Nov 27 '13 at 14:30