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.
As Jacob says, it can be useful to have mixtures of flags… but possibly you could indicate that somehow so that your detection doesn’t mind.
It shouldn’t be too hard to write a unit test which goes through every enum in an assembly decorated with
[Flags]and checks that there’s a value for 0 (possibly ensuring it’s calledNoneorDefault) and that every other defined value (fromEnum.GetValues()) is a power of two. You can check that usingif ((x & (x - 1)) == 0).You could potentially have something like an attribute
[Combination]to indicate values which are designed to be combinations… they could even indicate what flag names they’re meant to be combinations of, so you could check that too.I know this isn’t quite as good as a compile-time check, but assuming you’re already running tests regularly, it’s pretty close.