Code inspection: Bitwise operation on enum is not marked by [Flags] attribute
If an enumeration is being used as a combination of choices represented by bit flags rather than a set of single discrete values, it is recommended to decorate it with the [Flags] attribute.
This inspection reports cases where bitwise logical operators are applied to an enumeration that does not have the [Flags]
attribute.
If the enumeration indeed represents a set of bit flags, consider applying the [Flags]
attribute to it. This will help readers of your code better understand you intention, and it also will change the way some system methods, such as ToString()
and Enum.Parse()
handle the enumeration.
public enum Days
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
public class Test
{
public Test()
{
var weekEnd =
Days.Saturday | Days.Sunday;
Console.WriteLine(weekEnd);
// Output: 7
}
}
[Flags]
public enum Days
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
public class Test
{
public Test()
{
var weekEnd =
Days.Saturday | Days.Sunday;
Console.WriteLine(weekEnd);
// Output: Saturday, Sunday
}
}
Last modified: 04 June 2024