How to set all bits of enum flag

AFgone picture AFgone · Sep 19, 2011 · Viewed 22k times · Source

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)

Answer

leppie picture leppie · Sep 19, 2011

Easiest is probably:

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

For unsigned based enum:

enum Foo : uint
{
  blah = 1,
  ....
  all = ~0u;
}