The analyzer detected an enumeration declared with the 'Flags' (System.FlagsAttribute) attribute but lacking initializers for overriding the default values of the enumeration constants.
Consider the following example:
[Flags]
enum DeclarationModifiers
{
Static,
New,
Const,
Volatile
}
When declared with the 'Flags' attribute, an enumeration behaves not just as a set of named, mutually exclusive constants, but as a bit field, i.e. a set of flags whose values are normally defined as powers of 2, and the enumeration is handled by combining the elements with a bitwise OR operation:
DeclarationModifiers result = DeclarationModifiers.New |
DeclarationModifiers.Const;
If no initializers were set for the values of such an enumeration (default values are used instead), the values might overlap when combined. The example above is very likely to be incorrect and can be fixed in the following way:
[Flags]
enum DeclarationModifiers
{
Static = 1,
New = 2,
Const = 4,
Volatile = 8
}
Now the enumeration meets all the requirements for a bit field.
However, programmers sometimes leave the default values of the elements in such an enumeration on purpose, but then they should allow for every possible combination of values. For example:
[Flags]
enum Colors
{
None, // = 0 by default
Red, // = 1 by default
Green, // = 2 by default
Red_Green // = 3 by default
}
In this example, the programmer allowed for the overlapping values: a combination of 'Colors.Red' and 'Colors.Green' yields the value 'Colors.Red_Green', as expected. There is no error in this code, but it is only the code author who can establish this fact.
The following example shows the difference between the output of two enumerations marked with the 'Flags' attribute, one with and the other without value initialization:
[Flags]
enum DeclarationModifiers
{
Static, // = 0 by default
New, // = 1 by default
Const, // = 2 by default
Volatile // = 3 by default
}
[Flags]
enum DeclarationModifiers_Good
{
Static = 1,
New = 2,
Const = 4,
Volatile = 8
}
static void Main(....)
{
Console.WriteLine(DeclarationModifiers.New |
DeclarationModifiers.Const);
Console.WriteLine(DeclarationModifiers_Good.New |
DeclarationModifiers_Good.Const);
}
The corresponding outputs:
Volatile
New, Const
Since the 'DeclarationModifiers' enumeration uses default values, combining the constants 'DeclarationModifiers.New' and 'DeclarationModifiers.Const' results in the value 3, overlapping the constant 'DeclarationModifiers.Volatile', which the programmer might not expect. For the 'DeclarationModifiers_Good' enumeration, on the contrary, a combination of the flags DeclarationModifiers_Good.New ' and 'DeclarationModifiers_Good.Const' results in a correct value, which is a combination of both, as planned.
You can look at examples of errors detected by the V3121 diagnostic. |