Mark enums with FlagsAttribute

TypeName

MarkEnumsWithFlags

CheckId

CA1027

Category

Microsoft.Design

Breaking Change

NonBreaking

Cause

The values of a public enumeration are powers of two or are combinations of other values 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 with contiguous values.

Rule Description

An enumeration is a value type that defines a set of related named constants. Apply 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 days resources are available. If each resource's availability is encoded using the enumeration with 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 within 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 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 stored in the field.

How to Fix Violations

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

When to Exclude Warnings

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

Example

In the following example, DaysEnumNeedsFlags is an enumeration that meets the requirements for using FlagsAttribute, but does not have it. The ColorEnumShouldNotHaveFlag enumeration does not have values that are powers of two, but incorrectly specifies FlagsAttribute. This violates rule Do not mark enums with FlagsAttribute.

using System;

namespace DesignLibrary
{
// Violates rule: MarkEnumsWithFlags.

   public enum DaysEnumNeedsFlags 
   {
      None        = 0,
      Monday      = 1,
      Tuesday     = 2,
      Wednesday   = 4,
      Thursday    = 8,
      Friday      = 16,
      All         = Monday| Tuesday | Wednesday | Thursday | Friday
   }
   // Violates rule: DoNotMarkEnumsWithFlags.
   [FlagsAttribute]
   public enum ColorEnumShouldNotHaveFlag 
   {
      None        = 0,
      Red         = 1,
      Orange      = 3,
      Yellow      = 4
   }
}

Do not mark enums with FlagsAttribute

See Also

Reference

System.FlagsAttribute