4

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#?

Community
  • 1
  • 1
Saeed Neamati
  • 35,341
  • 41
  • 136
  • 188
  • 1
    If **any** combination of flags is valid you can simply check if each bit set to 1 in the `enum` value is a valid `enum` item (with a simple `for` and bitwise AND). – Adriano Repetti Aug 11 '12 at 08:41
  • In case you need an example of this just look the source code of `Enum.InternalFlagsFormat()` method (you won't build a string but you'll check if that value is valid). – Adriano Repetti Aug 11 '12 at 08:47
  • What if for any reason, the enumeration is not well-designed? For example it doesn't have `1`? In that case, 5 returns true, while 1 doesn't exist. – Saeed Neamati Aug 11 '12 at 08:49
  • @SaeedNeanmati you loop through bits of the **given** value. If, say, enumeration has these values: 2, 4, 8 and you give 5 what you'll do is a for that will result in 1, 2, 4, 8, etc. In this case if 2, 8, etc. aren't set so they'll skipped. 4 is valid but when you'll check if "1" (because it's set) is a valid enum value you'll see it's not. – Adriano Repetti Aug 11 '12 at 08:52

2 Answers2

5
  • 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
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
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();
}
James
  • 2,823
  • 22
  • 17