All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S3265.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

Enumerations are commonly used to identify distinct elements from a set of values.

However, they can also serve as bit flags, enabling bitwise operations to combine multiple elements within a single value.

// Saturday = 0b00100000, Sunday = 0b01000000, weekend = 0b01100000
var weekend = Days.Saturday | Days.Sunday;  // Combining elements

When enumerations are used as bit flags, it is considered good practice to annotate the enum type with the FlagsAttribute:

enum Permissions
{
  None = 0,
  Read = 1,
  Write = 2,
  Execute = 4
}

// ...

var x = Permissions.Read | Permissions.Write;  // Noncompliant: enum is not annotated with [Flags]

The FlagsAttribute explicitly marks an enumeration as bit flags, making it clear that it uses bit fields and is intended to be used as flags.

[Flags]
enum Permissions
{
  None = 0,
  Read = 1,
  Write = 2,
  Execute = 4
}

// ...

var x = Permissions.Read | Permissions.Write;  // Compliant: enum is annotated with [Flags]

Additionally, adding the FlagsAttribute to the enumeration enable a better string representation when using the Enum.ToString method.

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy