How to efficiently check an integer that is an enumeration with a flag?

Consider a FileAttributes enumeration for bitwise operations. I created a system in which the user selects some flags to determine the status of the file. The file can be either ReadOnly or System . Thus, the value will be 5 (1 for ReadOnly and 4 four System ).

How can I check if an integer is a valid enumeration of FileAttributes ?

I saw these questions, but they did not help me, since they do not work for beatified (marked, combined) values.

Verify that an integer type belongs to an enumeration member
Is there a way to check if an int is a legal enum in C #?

+4
source share
2 answers
  • compute cumulative bitwise "or" for all legal values ​​(possibly using Enum.GetValues)
  • compute "testValue and ~ allValues"
  • if it is nonzero, then it is not possible to form the current value by combining flags with rights
+5
source

It will work. Basically, if the combination of enumerations is invalid, ToString () will simply return the number.

 private bool CombinationValidForFileAttributes(int value) { return ((FileAttributes)value).ToString() != value.ToString(); } 
+2
source

All Articles