Description of the Rule
I’ve recently introduced a bug by using System.Enum.HasFlag
on an Enum that was not intended to be used as Flags. The rule should raise an error for the use of HasFlag
on an Enum without the [Flags]
annotation - or if no explicit integers are provided for the Enum-Fields.
The issue is, that a developer might rely on the HasFlag operation instead of equality comparison, which has a different result.
Code Example
public enum TransformOperation
{
None,
Position,
Rotation,
UniformScale,
NonUniformScale,
VertexOffset,
DownSkinning,
FlattenBottom
}
[Flags]
public enum TransformOperationFlags
{
None = 0,
Position = 1,
Rotation = 2,
UniformScale = 4,
NonUniformScale = 8,
VertexOffset = 16,
DownSkinning = 32,
FlattenBottom = 64,
}
...
[Fact]
public void HasFlag_Behavior()
{
// Non-compliant code
var a = TransformOperation.VertexOffset.HasFlag(TransformOperation.Position); // Returns true
// Compliant code
var b = TransformOperation.VertexOffset == TransformOperation.Position; // Returns false
}
Exceptions to the Noncompliant Code
The HasFlag
operation works on all Enums in C#. However, if an Enum is intended to be used as binary flags, the Enum is supposed to be annotated with Flags
. If explicit integer values for the Enum-Fields are provided, the use of HasFlag
might be correct and intended.
language specifications