.NET's built-in flag enum operations are unfortunately quite limited. Most of the time users are left with figuring out the bitwise operation logic.
In .NET 4, the method HasFlag
was added to Enum
which helps simplify user's code but unfortunately there are many problems with it.
HasFlag
is not type-safe as it accepts any type of enum value argument, not just the given enum type.
HasFlag
is ambiguous as to whether it checks if the value has all or any of the flags provided by the enum value argument. It's all by the way.
HasFlag
is rather slow as it requires boxing which causes allocations and thus more garbage collections.
Due in part to .NET's limited support for flag enums I wrote the OSS library Enums.NET which addresses each of these issues and makes dealing with flag enums much easier.
Below are some of the operations it provides along with their equivalent implementations using just the .NET framework.
Combine Flags
.NET flags | otherFlags
Enums.NET flags.CombineFlags(otherFlags)
Remove Flags
.NET flags & ~otherFlags
Enums.NET flags.RemoveFlags(otherFlags)
Common Flags
.NET flags & otherFlags
Enums.NET flags.CommonFlags(otherFlags)
Toggle Flags
.NET flags ^ otherFlags
Enums.NET flags.ToggleFlags(otherFlags)
Has All Flags
.NET (flags & otherFlags) == otherFlags
or flags.HasFlag(otherFlags)
Enums.NET flags.HasAllFlags(otherFlags)
Has Any Flags
.NET (flags & otherFlags) != 0
Enums.NET flags.HasAnyFlags(otherFlags)
Get Flags
.NET
Enumerable.Range(0, 64)
.Where(bit => ((flags.GetTypeCode() == TypeCode.UInt64 ? (long)(ulong)flags : Convert.ToInt64(flags)) & (1L << bit)) != 0)
.Select(bit => Enum.ToObject(flags.GetType(), 1L << bit))`
Enums.NET flags.GetFlags()
I'm trying to get these improvements incorporated into .NET Core and maybe eventually the full .NET Framework. You can check out my proposal here.