2

Why some values are in square brackets and what means 1<<1:

public enum PrivilegeFlags : int
{
    None = 0,
    [EnumMember(Value = "Agent")]
    Agent = 1 << 0,
    [EnumMember(Value = "Campaign")]
    Campaign = 1 << 1,
   [EnumMember(Value = "BlackList")]
    BlackList= 1 << 2,
All = (1 << 3) - 1
}

Thanks.

Simon
  • 1,955
  • 5
  • 35
  • 49
  • Second question is a duplicate of http://stackoverflow.com/questions/2493517/what-do-two-left-angle-brackets-mean-in-c – StuperUser May 19 '16 at 10:23

2 Answers2

2

The square brackets mean that it's an attribute, in this case specifically the EnumMemberAttribute. Also, << represents a left shift.

shree.pat18
  • 21,449
  • 3
  • 43
  • 63
2

It seems like the Enum is meant to create flags. You can see it more clearly if you translate the enum value into binary:

public enum PrivilegeFlags : int
{
    None = 0, //0000 0000
    [EnumMember(Value = "Agent")]
    Agent = 1 << 0, //0000 0001
    [EnumMember(Value = "Campaign")]
    Campaign = 1 << 1, //0000 0010
    [EnumMember(Value = "BlackList")]
    BlackList= 1 << 2, //0000 0100
    All = (1 << 3) - 1 //0000 0111
}

and EnumMember is an attribute assigned to the PrivilegeFlags enum members.

You do not need to declare the enum as shown as the following is equivalent enum:

public enum PrivilegeFlags : int
{
    None = 0, //0000 0000
    [EnumMember(Value = "Agent")]
    Agent = 1, //0000 0001
    [EnumMember(Value = "Campaign")]
    Campaign = 2, //0000 0010
    [EnumMember(Value = "BlackList")]
    BlackList= 4, //0000 0100
    All = 7 //0000 0111
}

1 << 1 means you have value of 1, and you do binary left-shift of 1 to the value of 1. It is clearly seen in the binary level:

0000 0001 //1 in binary
--------- << 1 shift left by 1
0000 0010 //note the binary shift, now this is actually 2

The benefit of using the specified left-shift << is to make the flag creation having incremental number: 0, 1, 2, 3, 4, ... etc instead of having number in the pattern of 2^n and 0: 0, 1, 2, 4, 8, ...

Ian
  • 30,182
  • 19
  • 69
  • 107