Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a [Flags] enum value for a single value

Tags:

c#

.net

enums

flags

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

like image 674
Jon Seigel Avatar asked Nov 02 '09 16:11

Jon Seigel


People also ask

Can an enum have one value?

Description. An enumeration. A string object that can have only one value, chosen from the list of values 'value1', 'value2', ..., NULL or the special '' error value. In theory, an ENUM column can have a maximum of 65,535 distinct values; in practice, the real maximum depends on many factors.

How do you find the value of an enum number?

Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

What are flags in enum?

Enum Flags Attribute The idea of Enum Flags is to take an enumeration variable and allow it hold multiple values. It should be used whenever the enum represents a collection of flags, rather than representing a single value. Such enumeration collections are usually manipulated using bitwise operators.

How do you check if an enum is valid?

Use the Object. values() method to get an array of the enum's values. Use the includes() method to check if the value exists in the array. The includes method will return true if the value is contained in the enum and false otherwise.


1 Answers

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;
like image 117
Henrik Avatar answered Oct 22 '22 01:10

Henrik