79690329

Date: 2025-07-04 14:24:18
Score: 0.5
Natty:
Report link

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.

Reasons:
  • Blacklisted phrase (0.5): thanks
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Criselmof