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
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.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With