Do not mark enums with FlagsAttribute

TypeName

DoNotMarkEnumsWithFlags

CheckId

CA2217

Category

Microsoft.Usage

Breaking Change

NonBreaking

Cause

The values of an enumeration are not powers of two, or combinations of powers of two defined by the enumeration, and the System.FlagsAttribute attribute is present.

Rule Description

An enumeration should have FlagsAttribute present only if each value defined in the enumeration is a power of two, or a combination of defined values.

How to Fix Violations

To fix a violation of this rule, remove FlagsAttribute from the enumeration.

When to Exclude Warnings

Do not exclude a warning from this rule.

Example

The following example shows an enumeration, Color, that contains the value 3, which is neither a power of two, nor a combination of any of the defined values. The Color enumeration should not be marked with the FlagsAttribute.

using System;

namespace UsageLibrary
{
   // The following enumeration correctly applies the attribute.
   [FlagsAttribute]
   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 ColorEnumShouldNotHaveFlags
   {
      None        = 0,
      Red         = 1,
      Orange      = 3,
      Yellow      = 4
   }
}

The following example shows an enumeration, Days, that meets the requirements for being marked with the System.FlagsAttribute.

Mark enums with FlagsAttribute

See Also

Reference

System.FlagsAttribute