All rules
CA1027Design Enabled by default: No

Mark enums with FlagsAttribute

Mark enums with FlagsAttribute

Microsoft docs

Description

An enumeration is a value type that defines a set of related named constants. Apply System.FlagsAttribute to an enumeration when its named constants can be meaningfully combined. For example, consider an enumeration of the days of the week in an application that keeps track of which day's resources are available. If the availability of each resource is encoded by using the enumeration that has System.FlagsAttribute present, any combination of days can be represented. Without the attribute, only one day of the week can be represented.

For fields that store combinable enumerations, the individual enumeration values are treated as groups of bits in the field. Therefore, such fields are sometimes referred to as *bit fields*. To combine enumeration values for storage in a bit field, use the Boolean conditional operators. To test a bit field to determine whether a specific enumeration value is present, use the Boolean logical operators. For a bit field to store and retrieve combined enumeration values correctly, each value that is defined in the enumeration must be a power of two. Unless this is so, the Boolean logical operators will not be able to extract the individual enumeration values that are stored in the field.

Cause

The values of an enumeration are powers of two or are combinations of other values that are defined in the enumeration, and the System.FlagsAttribute attribute is not present. To reduce false positives, this rule does not report a violation for enumerations that have contiguous values.

By default, this rule only looks at externally visible enumerations, but this is configurable.

How to fix violations

To fix a violation of this rule, add System.FlagsAttribute to the enumeration.

Example

#pragma warning disable CA1027
// The code that's violating the rule is on this line.
#pragma warning restore CA1027

When to suppress

Suppress a warning from this rule if you do not want the enumeration values to be combinable.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0