Flags and non-flags enumeration option

Let's say I need an enumeration both in flags and in an option other than flags.

  • Option 1: I could duplicate everything:

    enum Color { Red, Blue, Green } [Flags] enum Colors { None = 0, Red = 1, Blue = 2, Green = 4 } // use cases Color currentColor; Colors supportedColors; 
  • Option 2: I could just use the Flags option for everything:

     Colors currentColor; // ugly, since neither "None" nor "Red | Blue" should be valid 

I do not like any of them: in Option 1, Color.Red and Colors.Red are not completely connected, which may require code binding. In addition, I would have to synchronize the two rewrites. The disadvantage of option 2 is obvious. What I really like is something like

 enum Colors = Flag set of Color; 

Is there a more elgant solution to this requirement?

+4
source share
4 answers

I would just use the [Flags] version for everything and just ensure in several places that this is just one value. You need to do this anyway, because even without [Flags] the following is valid:

 var flags = (Color)47; // why not 

So, you need to check that Color is the one you expected anyway. [Flags] will be used only for serialization / parsing.

+5
source

The only possible flaw in option 2 ends with bits. If this is your problem, the listing checkbox is not suitable for you at all. Instead, make the supported colors a HashSet<Color>

+2
source

I had the same issue recently. Solved by option 2, with a simple check:

 bool IsColorValid(Color color) { return (color != 0 && (color & (color - 1)) == 0); } 
+2
source

Definitely do not create two enumerations called color and colors (option 1). This will make your code very confusing.

If I am missing something, I donโ€™t think option 2 is so ugly. In general, it is wise to initialize the system parameter with the default value of "None" before installing at run time.

+1
source

Source: https://habr.com/ru/post/1393126/


All Articles