Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flags- and non-flags-variant of an enum

Let's say I need both an enum both in a flags and in a non-flags variant.

  • 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 variant for everything:

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

I don't like either of these: In Option 1, Color.Red, and Colors.Red are completely unrelated, which might require binding code. In addition, I'd have to keep the two enums synchronized. The drawback of Option 2 is obvious. What I'd actually like is something like

enum Colors = Flag set of Color;

Is there a more elgant solution to this requirement?

like image 260
Heinzi Avatar asked Dec 27 '22 07:12

Heinzi


2 Answers

I would simply use the [Flags] version for everything, and simply ensure in a few places that it is only a single value. You need to do that either way, because even without [Flags] the following is valid:

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

So you need to check that the Color is one you were expecting anyway. The [Flags] will only help serialization/parsing.

like image 130
Marc Gravell Avatar answered Jan 06 '23 04:01

Marc Gravell


The only possible drawback of option 2 is running out of bits. If that's your problem, a flags enum is not suitible for you at all. Instead, make supported colors a HashSet<Color>

like image 21
zmbq Avatar answered Jan 06 '23 04:01

zmbq