Skip to content

[Analyzer Proposal]: Avoid Enum.HasFlag #90857

@Youssef1313

Description

@Youssef1313

Background and motivation

Enum.HasFlag was historically very problematic performance-wise. The situation has improved a lot in .NET Core 2.1 and many switched to using it again instead of the bitwise AND for readability.

However, per #55455 (comment):

Note that this optimization is not guaranteed to kick in. The optimization won't kick in Debug builds, in tier 0 JIT, or when the method is too big.

If the optimization isn't guaranteed to happen, I think it would make sense to still avoid it?

API Proposal

A new analyzer that will report a diagnostic when using x.HasFlag(y) where x and y are known to be of the same enum type at compile-time. There should be a code-fix that turns this to (x & y) != 0

API Usage

N/A

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationneeds-area-labelAn area label is needed to ensure this gets routed to the appropriate area owners

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions