Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set all bits of enum flag

I wonder a generic way for setting all bits of enum flag to 1. I just would like to have an enum which returns for all comparisons, regardless of other enums.

And this code works;

[Flags] public enum SomeRightEnum : uint {     CanDoNothing = 0,     CanDoSomething = 1 << 0,     CanDoSomethingElse = 1 << 1,     CanDoYetAnotherThing = 1 << 2,     ...     DoEverything = 0xFFFFFFFF  } 

But at the code above since it is uint we set the number of "F"s, it wouldn't work if it was int.

So I'll appreciate a generic way of setting all bits of enum flag to 1, regardless of the datatype (int, int64, uint etc)

like image 883
AFgone Avatar asked Sep 19 '11 07:09

AFgone


People also ask

What is flagged enum?

A flagged enum can be used to efficiently send and store a collection of boolean values. In a flagged enum, each value of the enum is assigned to a bit value. These must be bit values because each combination possible will be unique.

What is Flag attribute?

The [Flag] attribute is used when Enum represents a collection of multiple possible values rather than a single value.

Do enums have to be sequential?

There is nothing that requires them to be sequential. Your enum definition is fine and will compile without issue.

What is Flag in VB?

In general, "Flag" is just another term for a true/false condition. It may have more specific meanings in more specific contexts. For instance, a CPU may keep "arithmetic flags", each one indicating a true/false condition resulting from the previous arithmetic operation.


1 Answers

Easiest is probably:

enum Foo {   blah = 1,   ....   all = ~0 } 

For unsigned based enum:

enum Foo : uint {   blah = 1,   ....   all = ~0u; } 
like image 173
leppie Avatar answered Oct 04 '22 17:10

leppie