Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum assignment looks different

Tags:

c#

.net

c#-4.0

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

like image 654
Billa Avatar asked Dec 26 '22 17:12

Billa


1 Answers

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)
like image 141
dee-see Avatar answered Dec 28 '22 07:12

dee-see