How to show correct name on an Enum bitwise?

Asked

Viewed 125 times

5

I have this one marked as [Flag], ie, are values in bit

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

Setei to Both(both) position in 3 why if it is Left and Right at the same time, it must be equal to Both (1+2=3) But when I call Both at the Tostring and it shows up as "Left | Right". How do I make him appear as "Both"?

1 answer

3


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

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

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

Still you can do it:

Position pos = Position.Left | Position.Right;

And when it comes to bitwise testing, you can use bitwise operator &, so as to isolate the desired bit, thus:

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

Or else the other way around:

if ((pos & Position.Left) == 0)
{
    // código para quando o bit Position.Left está zerado
}
  • Yes, I hope so Both as 3 because its default would be 4 with [Flags]. It is that in certain parts of code I always need to compare the following: GameResult.PlayerPirate = playAs == Position.Right || playAs == Position.Both ? PlayerType.Human : PlayerType.Computer; Then if it is Left or Both do such a thing. But thank you very much, that was quite the mistake.

  • 2

    I added detail on how to do the check more simply.

  • 1

    Yes, the way I did in the other comment is before I knew that there was bitwise (: then I went to use and the doubt arose. This will greatly simplify the checks here, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.