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

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

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

When you annotate an Enum with the Flags attribute, you must not rely on the values that are automatically set by the language to the Enum members, but you should define the enumeration constants in powers of two (1, 2, 4, 8, and so on). Automatic value initialization will set the first member to zero and increment the value by one for each subsequent member. As a result, you won’t be able to use the enum members with bitwise operators.

Exceptions

The default initialization of 0, 1, 2, 3, 4, …​ matches 0, 1, 2, 4, 8 …​ in the first three values, so no issue is reported if the first three members of the enumeration are not initialized.

How to fix it

Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on.

Code examples

Noncompliant code example

var bananaAndStrawberry = FruitType.Banana | FruitType.Strawberry;
Console.WriteLine(bananaAndStrawberry.ToString());  // Will display only "Strawberry"

[Flags]
enum FruitType    // Noncompliant
{
  None,
  Banana,
  Orange,
  Strawberry
}

Compliant solution

var bananaAndStrawberry = FruitType.Banana | FruitType.Strawberry;
Console.WriteLine(bananaAndStrawberry.ToString()); // Will display "Banana, Strawberry"

[Flags]
enum FruitType
{
  None = 0,
  Banana = 1,
  Orange = 2,
  Strawberry = 4
}

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy