May 5, 2021

c# GetUniqueFlags for Flags Enum

Use this to get unique flags from a combined flags enum value
public static class EnumFlagExtensions
{
    // https://stackoverflow.com/questions/4171140/how-to-iterate-over-values-of-an-enum-having-flags
    public static IEnumerable<T> GetUniqueFlags<T>(this T value)
        where T : Enum
    {
        // if it's not a flag enum, return empty
        Debug.Assert(value.GetType().IsDefined(typeof(FlagsAttribute), false), 
          "Not a \"Flags\" enum type");
        if (!value.GetType().IsDefined(typeof(FlagsAttribute), false))
          yield break;

        var valueLong = Convert.ToUInt64(value, CultureInfo.InvariantCulture);
        foreach (var enumValue in value.GetType().GetEnumValues())
        {
            if (
                enumValue is T flag // cast enumValue to T
                // convert flag to ulong
                && Convert.ToUInt64(flag, CultureInfo.InvariantCulture) is ulong bitValue 
                && (bitValue & (bitValue - 1)) == 0 // is this a single-bit value?
                && (valueLong & bitValue) != 0 // is the bit set?
                )
            {
                yield return flag;
            }
        }
    }
}