Flag enums without power of two values
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.
I never tried it myself, but maybe you could write a custom rule for FxCop.
Check FxCop and Code Analysis: Writing Your Own Custom Rules.
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 called None
or Default
) and that every other defined value (from Enum.GetValues()
) is a power of two. You can check that using if ((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.