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.
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.
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:The suggestion is to add 2 methods to Enum to help set and clear a flag.
These methods should be aggressively inlined since bitwise manipulations is very likely to be used in a performance sensitive scenario.