19

Ok so I am new to C#, and for the life of me I cannot comprehend what exactly the below code (from a legacy project) is supposed to do:

[Flags]
public enum EAccountStatus
{
    None = 0,
    FreeServiceApproved = 1 << 0,
    GovernmentAccount = 1 << 1,
    PrivateOrganisationAccount = 1 << 2,
    All = 8
}

What exactly does the << operator do here on the enums? Why do we need this?

Joel Min
  • 3,387
  • 3
  • 19
  • 38

2 Answers2

27

Behind the scenes, the enumeration is actually an int.
<< is the Bitwise Left Shift Operator
An equivalent way of writing this code is :

[Flags]
public enum EAccountStatus
{
    None = 0,
    FreeServiceApproved = 1,
    GovernmentAccount = 2,
    PrivateOrganisationAccount = 4,
    All = 8
}

Please note, that this enumeration has the Flag attribute

As stated in the msdn:

Use the FlagsAttribute custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value.

This way, if you want to have multiple options set you can use:

var combined =  EAccountStatus.FreeServiceApproved  | EAccountStatus.GovernmentAccount 

which is equivalent to:

  00000001  // =1 - FreeServiceApproved 
| 00000010  // =2 - GovernmentAccount 
 ---------
  00000011  //= 3 - FreeServiceApproved  and  GovernmentAccount 

this SO thread has a rather good explanation about the flags attribute

Community
  • 1
  • 1
Avi Turner
  • 10,234
  • 7
  • 48
  • 75
  • Thanks Avi, that was beautifully explained :) – Joel Min Jun 21 '16 at 06:09
  • :) I'm glad I could be of help. – Avi Turner Jun 21 '16 at 06:11
  • 2
    There shouldn't be an ALL ("all flags") option on FLAGS. The combination of all the flags here would be 7, not 8, which results in 2 values meaning ALL. A solution to this is to binary OR all options, but a bug will almost certainly appear when another enum is added and a dev doesn't update the ALL enum. Another problem is if the value 8 is used when storing data, then the flag enum EAccountStatus is effectively sealed meaning no more options can be added without modifying stored data. Besides reporting, it's rare that you will need to check for ALL. – Dan Jan 11 '21 at 06:50
  • 1
    @Dan Agreed. The answer was simply using the example used in the original question. – Avi Turner Jan 12 '21 at 05:20
  • @AviTurner no worries, it wasn't really at you. Was leaving it here for people that don't know better – Dan Jan 13 '21 at 17:00
  • 1
    I read a handful of bitwise shift articles and watched a video, explaining how the bits get shifted.. all the while missing the context of why we'd do this in the first place. This answer was exactly what I needed to read. – DontFretBrett Jul 02 '21 at 21:53
2

<< is doing simply what does i.e. Shift left operation.

As far as why in an enum is concerned, its just a way of evaluating the expression as enums allow expressions (and evaluate them on compile time)

Failed Scientist
  • 1,977
  • 3
  • 29
  • 48