S4070 — Non-flags enums should not be marked with "FlagsAttribute"

Language
C#
Type
Code smell
Severity
Major

Why is this an issue?

This rule raises an issue when an externally visible enumeration is marked with FlagsAttribute and one, or more, of its values is not a power of 2 or a combination of the other defined values.

Noncompliant code example


using System;

namespace MyLibrary
{
    [Flags]
    public enum Color // Noncompliant, Orange is neither a power of two, nor a combination of any of the defined values
    {
        None    = 0,
        Red     = 1,
        Orange  = 3,
        Yellow  = 4
    }
}

Compliant solution


using System;

namespace MyLibrary
{
    public enum Color // Compliant - no FlagsAttribute
    {
        None = 0,
        Red = 1,
        Orange = 3,
        Yellow = 4
    }

    [Flags]
    public enum Days
    {
        None = 0,
        Monday = 1,
        Tuesday = 2,
        Wednesday = 4,
        Thursday = 8,
        Friday = 16,
        All = Monday| Tuesday | Wednesday | Thursday | Friday    // Compliant - combination of other values
    }
}

↑ Back to top