A quick and readable answer to obtaining all bitflags of a [Flags] enum BitFlags
is
BitFlags bitFlags = Enum.GetValues<BitFlags>().Aggregate((a, b) => a | b);
For improved code quality, it should be put into a method. But unfortunately, doing that is a pain. The simplest way I found needs reflection and object-casting.
using System.Linq;
static class EnumExtension<T> where T : struct, Enum
{
public readonly static T AllFlags;
static EnumExtension()
{
var values = typeof(T).GetFields().Where(fi => fi.IsLiteral).Select(fi => (int)fi.GetRawConstantValue());
AllFlags = (T)(object)(values.Aggregate((a, b) => a | b));
}
}
It can be used as EnumExtension<BitFlags>.AllFlags
and is only computed once for each enum, thanks to the static constructor.
C#14 comes with static property extensions for types, so we hopefully could write BitFlags.AllFlags
then using an extension
block.