Search code examples
c#enumsflags

Flags enum strange values


[Flags]
public enum Direction
{
    None = 0x0000,
    Left = 0x0001,
    Right = 0x0002,
    Up = 0x0004,
    Down = 0x0008,
    Forward = 0x0016,
    Backward = 0x0032
}

Really confused, I'm using using this enum in an if statement like so:

if ((enumValues & Direction.Forward) == Direction.Forward)
{
    // do stuff
}

to check if it contains a flag inside the collection.

if ((enumValues & Direction.Right) == Direction.Forward)
{
    // do stuff
}

Keeps running this if ( Direction.Right ) code despite not containing the Right flag inside the collection, I've even debugged it with breaks and the value doesn't contain Direction.Right but it's still returning true and running the snippet.

Have I set up my enum wrong or am I querying the values wrong?

I don't use flags normally I just figured it would be a good use of them.


Solution

  • Seeing how you have defined your enum:

    None = 0x0000,
    Left = 0x0001,
    Right = 0x0002,
    Up = 0x0004,
    Down = 0x0008,
    Forward = 0x0016,
    Backward = 0x0032
    

    You are confusing hexadecimal and decimal numbers.

    In a [Flags] enum, the binary representation of the values of your enum should be something like this:

    0000 0000 0000 0000 0000 0000 0000 0001
    0000 0000 0000 0000 0000 0000 0000 0010
    0000 0000 0000 0000 0000 0000 0000 0100
    0000 0000 0000 0000 0000 0000 0000 1000
    

    Which in decimal, are powers of 2: 1, 2, 4, 8, 16 etc

    But the way you are writing the values start with 0x, which denotes a hexadecimal value. So you are actually setting the values for the enum case as the hex numbers 1, 2, 4, 8 and 16.

    You should remove those 0x:

    None = 0,
    Left = 1,
    Right = 2,
    Up = 4,
    Down = 8,
    Forward = 16,
    Backward = 32