2

I have a enum like

enum Test
{ 
    A = -2,
    B = -1 , 
    C = 0 , 
    D = 1 , 
    E = 2
}

and , how can i judge a enum value is in a combine enum values

class Program
{
    static void Main(string[] args)
    {
        Test t1 = Test.A | Test.E;

        Console.WriteLine((t1 & Test.E) > 0); // true
        Console.WriteLine((t1 & Test.A) > 0); // why this is false ?

        Console.ReadKey();
    }
}

i want to ask about , why

Test t1 = Test.A | Test.E;

but

Console.WriteLine((t1 & Test.A) > 0);

Thanks....

UPDATE:

Thank you for your comment , and the good design...

*I think I will change the bad design as sonn as quickly!! *

*Thank you all the same . (^^ メ)*

2 Answers 2

3

To make this work, you have to make sure that the enum-values set different bits since you are doing a bitwise-and operation. Try to define Test like this

enum Test
{ 
    A = 1,
    B = 2, 
    C = 4, 
    D = 8, 
    E = 16
}

Alternatively.

[Flags]
enum Test
{ 
    A = 0x1,
    B = 0x2, 
    C = 0x4, 
    D = 0x8, 
    E = 0x10
}
Sign up to request clarification or add additional context in comments.

13 Comments

I don't think the second example does what you think it does. A = 0, B = 1, C = 2, ...
Thanks for your comment, I know if I did I would defined it like that , But I cannt change it now.... sorry...
Scott - That's the only way to get it work in this way you want. With you enum definition, how can you tell if D is selected alone, or if C and D is selected together? All in all, an enum is just an int, and for D and C,D this int is 2.
I dont think you're remark about default enum values are correct. From the enum-documentation: "By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.". I can't find an exception for FlagsAttribute.
@Scott: Your enthusiasm is infectious but your solution is still flawed. Try Test t1 = Test.A and yet (t1 & Test.D) == Test.D is true!
|
2

The reason is that Test.A | Test.E evaluates to -2 | 2 = -2, so t1 == Test.A.

Now t1 & Test.E = -2 & 2 = 2 > 0 and t1 & Test.A = -2 & -2 = -2 < 0

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.