Brondahl
Brondahl

Reputation: 8557

C# Check if Flags enum has only one value set

I have a Flags enum and want to assert that a given instance of it, is one of the primitive values, i.e. it has exactly one '1' in its binary representation, i.e. it's a power of two.

What's the best way to check this?

(I suppose "best" isn't necessarily well-defined, so ...)

Upvotes: 1

Views: 2352

Answers (2)

Fabian
Fabian

Reputation: 1190

Using Framework functionality and be more flexible concerning the number of set flags one could use something like:

[Flags] 
public enum FlagsEnum {
   None = 0,
   One = 1,
   Two = 2,
   Three = 4,
}

void Main()
{
    var flags = FlagsEnum.Two;
    var hasOneElement = Enum.GetValues(typeof(FlagsEnum)).OfType<FlagsEnum>().Where(i => i != FlagsEnum.None && flags.HasFlag(i)).Count() == 1;
}

Upvotes: 0

TheDude
TheDude

Reputation: 267

bit operation will yield the fastest result

((anInstanceOfTheFlaggedEnum & (anInstanceOfTheFlaggedEnum -1)) != 0)

over the more readable built in function

Enum.IsDefined(typeof(yourFlaggedEnumType), anInstanceOfTheFlaggedEnum)

I just ran a test and it was ~175 times faster..

Upvotes: 4

Related Questions