# V3059. Consider adding '[Flags]' attribute to the enum.

The analyzer detected a suspicious enumeration whose members participate in bitwise operations or have values that are powers of 2. The enumeration itself, however, is not marked with the [Flags] attribute.

If one of these conditions is true, the [Flags] attribute must be set for the enumeration if you want to use it as a bit flag: it will give you some advantages when working with this enumeration.

For a better understanding of how using the [Flags] attribute with enumerations changes the program behavior, let's discuss a couple of examples:

    enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }

    // en1: 5
    var en1 = (Suits.Spades | Suits.Diamonds);

Without the [Flags] attribute, executing the OR bitwise operation over the members with the values '1' and '4' will result in the value '5'.

It changes when [Flags] is specified:

    [Flags]
    enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }

    // en2: SuitsFlags.Spades | SuitsFlags.Diamonds;
    var en2 = (SuitsFlags.Spades | SuitsFlags.Diamonds);

In this case, the result of the OR operation is treated not as a single integer value, but as a set of bits containing the values 'SuitsFlags.Spades' and 'SuitsFlags.Diamonds'.

If you call to method 'ToString' for objects 'en1' and 'en2', the results will be different, too. This method attempts to convert numerical values to their character equivalents, but the value '5' has no such equivalent. However, when the 'ToString' method discovers that the enumeration is used with the [Flags] attribute, it treats the numerical values as sets of bit flags. Therefore, calling to the 'ToString' method for objects 'en1' and 'en2' will result in the following:

    String str1 = en1.ToString(); // "5"
    String str2 = en2.ToString(); // "SuitsFlags.Spades |
                                  //  SuitsFlags.Diamonds"

In a similar way, numerical values are obtained from a string using static methods 'Parse' and 'TryParse' of class 'Enum'.

Another advantage of the [Flags] attribute is that it makes the debugging process easier, too. The value of the 'en2' variable will be displayed as a set of named constants, not as simply a number:

References:

- What does the [Flags] Enum Attribute mean in C#?
- CLR via C#. Jeffrey Richter. Chapter 15 - Enumerated Types and Bit Flags.