The MSDN documentation for the Flag
attribute says that you should:
Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap.
...and of course I always try to remember to do that. However, nothing enforce that and if you just create an enumeration the 'basic' way like...
[Flags]
public enum BrokenEnum
{
None,
FirstOption,
SecondOption,
ThirdOption
}
...it won't behave as expected. To combat this, I'm looking for some kind of static code analysis (like FxCop) that can warn me when an enum like the one above exists in my code. The closest such warning I could find was 'CA1008: Enums should have zero value' - which is also helpful for designing flags enumeration correctly but isn't enough.
What is the best way to find incorrectly designed flags enums in my code? The more automated the solution, the better.
Sometimes you want to have a flags enum that represents multiple options; in cases like that, it's not an error. Here's a common example:
[Flags]
public enum FilePermissions
{
None = 0,
Read = 1,
Write = 2,
Execute = 4,
ReadWrite = 3, // Read | Write,
ReadWriteExecute = 7 // Read | Write | Execute
}
Perhaps because of the need to support cases like these, that's why a compiler doesn't cause a warning or error.
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