-1

What is the difference between

[Flags]
    public enum AnswerFlags
    {
    A = (1 << 2),
    B = (1 << 1),
    C = (1 << 0)
    }

and

  public enum AnswerFlags
        {
        A = 4,
        B = 2,
        C = 1
        }

And why should i work with bits instead of integers?

lolex
  • 65
  • 11
  • Duplicate of the question here http://stackoverflow.com/a/8480/3856907 – Erik Jul 20 '16 at 21:02
  • Bits are often useful when working with hardware ports and registers. They can also be useful in some situations when extremely compact representation is more important than clarity of code. – Eric J. Jul 20 '16 at 21:04
  • This question answers it for you: http://stackoverflow.com/questions/8447/what-does-the-flags-enum-attribute-mean-in-c?rq=1 – Eric Vaughan Jul 20 '16 at 21:08
  • This not a duplicate of the question linked to. This is about the way to define the values, either as shift expressions or literals. – Martin Maat Jul 20 '16 at 21:20
  • It would be more common to go the other way (start with 1 and double each next value). As for the difference, the resulting values will be the same but a progression of 1,2,3, et cetera looks more natural and the shift left expression expresses the bit masks more explicitly. It is clear that for each value only one bit is set and that the bit moves left one step for every next value. It is also harder to do it wrong because adding 1 each time is easier than doubling growing decimal numbers. I never saw this way of declaring flags before but I like it and I will adopt it. – Martin Maat Jul 20 '16 at 21:20

1 Answers1

1

The core difference between flags and classic enums is that enum holds only one value: A or B or C while flags are meant to hold sets of values: A or B or C or AB or AC or BC or ABC.

You may want to read about it here: MSDN