Icerman
Icerman

Reputation: 1119

Flag enum with shared values depending on context?

I want design a flag enum but shared by two use cases:

For example: I have defined the following

[Flags]
public enum Answer
{
    Yes = 1, 
    No = 2,
    Choice1 = 1,
    Choice2 = 2,
    Choice3 = 4,
    Choice4 = 8,
}

The reason to combine this is to share a consistent interface(e.g. process answer). Are there any arguments against this design? Thanks!

Upvotes: 2

Views: 169

Answers (3)

Eugen Rieck
Eugen Rieck

Reputation: 65334

[Flags]
public enum Answer
{
    No = 0, 
    Choice1 = 1,
    Choice2 = 2,
    Choice3 = 4,
    Choice4 = 8,
    Yes = 0x80000000,
}

Upvotes: 2

Senthil
Senthil

Reputation: 106

1) If you want to check whether the question is being answered or not then you can check for value 1 (if the value 1 Means it is not answered). 2) If any of the choices is set then you can assume that your answered is being answered.

public enum Answer {
  No = 1,     
  Choice1 = 2,     
  Choice2 = 3,     
  Choice3 = 4,     
  Choice4 = 8
} 

Hope this helps!

Upvotes: 0

user596075
user596075

Reputation:

I wouldn't do this. Here's why:

class Program
    {
        [Flags]
        public enum Answer
        {
            Yes = 1,
            No = 2,
            Choice1 = 1,
            Choice2 = 2,
            Choice3 = 4,
            Choice4 = 8,
        }

        static void Main(string[] args)
        {

            int SomeInt = (int)Answer.Choice1;

            Console.WriteLine((Answer)SomeInt);

            Console.ReadKey();
        }
    }

The result of that is

"Yes"

It makes sense, and obviously it is syntactically correct, but you are making it very hard to maintain an enumeration like that. It is going to match on the first correct value of the enumeration. That is logic that I believe can be improved upon so that confusion is limited/eliminated.

Would I do this? No.

Upvotes: 1

Related Questions