Testing a [Flags] enum value for a single value
Asked Answered
M

3

10

If I have an enum that's marked with [Flags], is there a way in .NET to test a value of this type to see if it only contains a single value? I can get the result I want using bit-counting, but I'd rather use built-in functions if possible.

When looping through the enum values dynamically, Enum.GetValues() returns the combination flags as well. Calling that function on the enum in the following example returns 4 values. However, I don't want the value combinations included in the inner algorithm. Testing individual enum values for equality is out, since the enum could potentially contain many values, and it also requires extra maintenance when the values in the enum change.

[Flags]
enum MyEnum
{
    One = 1,
    Two = 2,
    Four = 4,
    Seven = One | Two | Four,
}

void MyFunction()
{
    foreach (MyEnum enumValue in Enum.GetValues(typeof(MyEnum)))
    {
        if (!_HasSingleValue(enumValue)) continue;

        // Guaranteed that enumValue is either One, Two, or Four
    }
}

private bool _HasSingleValue(MyEnum value)
{
    // ???
}



Related: StackOverflow: Enum.IsDefined on combined flags

Minestrone answered 2/11, 2009 at 16:0 Comment(0)
D
20

You can cast it to int and use the techniques from Bit Twiddling Hacks to check if it's a power of two.

int v = (int)enumValue;
return v != 0 && (v & (v - 1)) == 0;
Dehorn answered 2/11, 2009 at 16:4 Comment(1)
+1. While definitely not the most transparent technique, it's undoubtedly the simplest.Sooksoon
C
0

You can use a combination of IsDefined and checking for powers of 2.

Chess answered 2/11, 2009 at 16:4 Comment(1)
In the example I wrote, IsDefined would always evaluate to true.Minestrone
S
-1

You could you Enum.GetValues and count only those items that are a power of 2 (evenly divisible by 2 with no remainder).

Sinful answered 2/11, 2009 at 16:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.