[ How to effectively validate an integer that represents a flagged enumeration? ]

Consider FileAttributes enumeration which is designed for bitwise operations. I've created a system in which, user selects some checkboxes to determine the status of a file. A file may be both ReadOnly and System. Thus the value would be 5 (1 for ReadOnly and 4 four System).

How can I validate an integer to be a valid FileAttributes enumeration?

I've seen these questions, but they didn't help me, as they don't work for bitwised (flagged, combined) values.

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

Answer 1


  • compute a cumulative bitwise "or" over all legal values (perhaps using Enum.GetValues)
  • compute "testValue & ~allValues"
  • if that is non-zero, then it is impossible to form your current value by combining the legal flags

Answer 2


This will work. Basically, if the enum combination is invalid, ToString() will just return the number.

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