How to display correct name in a bitwise enum?

5

I have the following enum marked as [Flag] , that is, they are values in bit

[Flags]
public enum Position
{
    None,
    Left,
    Right,
    Both=3
}

Sete for Both (both) position in 3 because if it is Left and Right at the same time, it should equal Both (1 + 2 = 3) But when I call Both on the ToString and it appears as "Left | Right" . How do I make it appear as "Both" ?

    
asked by anonymous 13.04.2014 / 21:12

1 answer

3

Remove the Flags attribute ... because that is exactly what the Flags attribute is for, to indicate that there is a combination of values ... if you want to display a value without considering it as a combination, then why use Flags ?

Note that an enum does not require the Flags attribute to be used as such. Also, I would specify the values all manually to prevent future errors:

public enum Position
{
    None - 0,
    Left = 1,
    Right = 2,
    Both = 3
}

You can still do this:

Position pos = Position.Left | Position.Right;

And at the time of the bitwise test, you can use the bitwise & operator , to isolate the desired bit, like this:

if ((pos & Position.Left) != 0)
{
    // código para quando o bit Position.Left está definido
}

Or the opposite:

if ((pos & Position.Left) == 0)
{
    // código para quando o bit Position.Left está zerado
}
    
13.04.2014 / 21:24