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);
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