3

I'm trying to know if a enum value has defined all flags. The enum is defined as following:

[Flags]
public enum ProgrammingSkills
{
    None = 0,
    CSharp = 1,
    VBNet = 2,
    Java = 4,
    C = 8,
}

I cannot change the enum to define 'All', because that enum is defined in a dll library.

Of course I can iterate over all enum values, but is there any better/shorter/smarter way to determine if a enum value has defined ALL values?


EDIT:

I would like to have working code even the enum changes.

halfer
  • 19,824
  • 17
  • 99
  • 186
Daniel Peñalba
  • 30,507
  • 32
  • 137
  • 219

5 Answers5

6

I don't know if it's better but it is definitely shorter and will work if you modify the enum in the future:

bool result = Enum.GetValues(typeof(ProgrammingSkills))
      .Cast<ProgrammingSkills>()
      .All(enumValue.HasFlag);
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
3

You could do the following:

var hasAll = val == (ProgrammingSkills.CSharp | ProgrammingSkills.VBNet
    | ProgrammingSkills.Java | ProgrammingSkills.C);

Or shorter, but not really good for maintenance:

var hasAll = (int)val == 15; // 15 = 1 + 2 + 4 + 8

Or in a generic way:

var hasAll = (int)val == Enum.GetValues(typeof(ProgrammingSkills))
                             .OfType<ProgrammingSkills>().Sum(v => (int)v);
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
0
ProgrammingSkills ps = ProgrammingSkills.None | ProgrammingSkills.CSharp | ProgrammingSkills.VBNet | ProgrammingSkills.Java | ProgrammingSkills.C;

int total = (int)ps;

if (total == 15) return true;//ALL FLAGS THERE
Adrian Nasui
  • 1,054
  • 9
  • 10
0

You can test for all members:

bool allSet = value & (ProgrammingSkills.CSharp
                    | ProgrammingSkills.VBNet
                    | ProgrammingSkills.Java
                    | ProgrammingSkills.C) != 0;

The | creates a mask containing all possible values, which is tested (&) against value, containing the enum you want to test.

But that is error-prone and isn't really maintainable. You might want to stick to a loop.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • 1
    I can only assume the down vote is for missing `ProgrammingSkills.C`? But you clearly get the point across. – juharr Dec 17 '14 at 12:03
  • Reading the code, I'd think this just test if *any* of the bits are set instead of *all*. – Dejan Jul 13 '23 at 09:13
  • @Dejan you appear to be right. To test for _all_ values, the `&` should become an `==` and the `!= 0` can be dropped. – CodeCaster Jul 13 '23 at 09:54
-1

You can cast your enum to int and check if the value than is 15 (sum of all enum-flags):

ProgrammingSkills programmingSkills = ProgrammingSkills.CSharp | ProgrammingSkills.VBNet | ProgrammingSkills.Java | ProgrammingSkills.C;
int programmingSkillsValue = (int)programmingSkills;
if(programmingSkillsValue == 15)
{
  // All Flags are set
}
Tomtom
  • 9,087
  • 7
  • 52
  • 95