Skip to content

Add Enum.SetFlag and Enum.RemoveFlag to make bitwise flagging easier #14084

Description

@yufeih

To maintain multiple bool states in a class, instead of declaring many bool fields, an enum flag can be used to compact these states in to a single member to optimize for memory usage.

[Flags] enum DirtyFlags { X = 1, Y = 1 << 1, Z = 1 << 2 };

DirtyFlags dirtyFlags = DirtyFlags.X | DirtyFlags.Y | DirtyFlags.Z;

It is simple to test if a flag is set using Enum.HasFlag(DirtyFlags.X), but the scenario is not complete. Without the ability to set and remove a flag, the following code needs to be maintained manually:

// Setting a flag
dirtyFlags |= DirtyFlags.X;
// Removing a flag, this is harder to remember :(
dirtyFlags &= ^DirtyFlags.X;

The suggestion is to add 2 methods to Enum to help set and clear a flag.

public bool HasFlag(Enum flag); // This method already exists
public bool SetFlag(Enum flag);
public bool RemoveFlag(Enum flag);

These methods should be aggressively inlined since bitwise manipulations is very likely to be used in a performance sensitive scenario.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workAPI needs work before it is approved, it is NOT ready for implementationarea-System.Runtime

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions