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.
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);
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);
ProgrammingSkills ps = ProgrammingSkills.None | ProgrammingSkills.CSharp | ProgrammingSkills.VBNet | ProgrammingSkills.Java | ProgrammingSkills.C;
int total = (int)ps;
if (total == 15) return true;//ALL FLAGS THERE
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.
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.