Rule to raise a bug for HasFlag usage on Non-Flag Enums

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

    public enum TransformOperationFlags
        None = 0,
        Position = 1,
        Rotation = 2,
        UniformScale = 4,
        NonUniformScale = 8,
        VertexOffset = 16,
        DownSkinning = 32,
        FlattenBottom = 64,

        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

Hello @mathias_vetsch,

Thank you for reaching out, that’s a very nice rule idea!

I have created an issue in the C# analyzer repository. You can check it here.

Regarding the exception you suggest, as stated in the Enum.HasFlag documentation, it is intended to only be used with enums marked with [Flags].
Considering this, I don’t think this exception should be added to the rule.

Have a nice weekend!

1 Like