Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-3265

Non-flags enums should not be used in bitwise operations

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Hide
      * Mark enum "XXX" with "Flags" attribute or remove this bitwise operation.
      * Remove this bitwise operation; the enum "XXX" is not marked with "Flags" attribute.
      Show
      * Mark enum "XXX" with "Flags" attribute or remove this bitwise operation. * Remove this bitwise operation; the enum "XXX" is not marked with "Flags" attribute.
    • Default Severity:
      Critical
    • Impact:
      High
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      C#
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      2min
    • Analysis Scope:
      Main Sources, Test Sources
    • FxCop:
      MarkEnumsWithFlags
    • ReSharper:
      BitwiseOperatorOnEnumWithoutFlags

      Description

      enum}}s are usually used to identify distinct elements in a set of values. However {{enum}}s can be treated as bit fields and bitwise operations can be used on them to combine the values. This is a good way of specifying multiple elements of set with a single value. When {{enum}}s are used this way, it is a best practice to mark the {{enum with the FlagsAttribute.

      Noncompliant Code Example

      enum Permissions
      { 
        None = 0,
        Read = 1,   
        Write = 2, 
        Execute = 4 
      }
      // ...
      
      var x = Permissions.Read | Permissions.Write;  // Noncompliant; enum is not marked with [Flags]
      

      Compliant Solution

      [Flags]
      enum Permissions
      { 
        None = 0,
        Read = 1, 
        Write = 2, 
        Execute = 4
      }
      // ...
      
      var x = Permissions.Read | Permissions.Write;
      

        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            ann.campbell.2 Ann Campbell
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Dates

              Created:
              Updated: