0

I must be doing something very stupid but I can't see what. In a simple console app I have;

[Flags]
public enum ConsoleStates : byte
{
    TopLevel,
    All,
    MainMenu,
    SingleLeagueSelected,
}

then

public class Program
{
    static void Main(string[] args)
    {
        Program p = new Program();
        p.StartUp(args);
    }

    private bool CheckFlag(ConsoleStates targetVal, ConsoleStates checkVal)
    {
        return ((targetVal & checkVal) == checkVal);
    }

    private void StartUp(string[] args)
    {
        int x = 0;
        ConsoleStates states = (ConsoleStates.All | ConsoleStates.MainMenu);
        if (CheckFlag(states, ConsoleStates.SingleLeagueSelected))
        {
            x++;
        }
     }
}

My problem X should be zero at the end but it is always 1. As I understand it, it should do a bit wise AND operation and check to see if singleleagueSelected is in there and return false.

It is very odd and all my googling says this is very simple and just works, but for the life of me I can't get it. /hangs head in shame.

Jon
  • 15,110
  • 28
  • 92
  • 132
  • "hangs head in shame"... as well you should. This problem would have been very easy to find using the debugger, if you had only tried. SO should not replace a debugger, ask a question when you've tried single-stepping and are still stuck. – Ben Voigt Nov 15 '11 at 23:14
  • @BenVoigt I did repeatedly try the debugger and step through what was going on. Don't make assumptions! – Jon Nov 16 '11 at 07:24

3 Answers3

5

Enums will have values 0, 1, 2, 3, ... by default. AFAIK adding FlagsAttribute doesn't change this. I think you need to explicitly set the values you want, e.g.:

[Flags]
public enum ConsoleStates : byte
{
    TopLevel = 0,
    All = 1,
    MainMenu = 2,
    SingleLeagueSelected = 4,
}
Dennis
  • 2,132
  • 3
  • 21
  • 28
  • You are correct about the FlagsAttribute. http://stackoverflow.com/questions/5902967/what-does-the-flags-attribute-really-do – Ritch Melton Nov 15 '11 at 23:19
  • AH, that may have been my mistake then. I thought that it did the correct bit wise values needed by default. – Jon Nov 16 '11 at 07:25
2

You enum is numbered consecutively starting at 0. To use bit flags, you will need to manually number them as powers of 2.

drdwilcox
  • 3,833
  • 17
  • 19
1

If you are using .NET 4.0, you can use Enum.HasFlag() method to check if an enum contains a specific bit value. See my answer in this question.

Community
  • 1
  • 1
Bryan Crosby
  • 6,486
  • 3
  • 36
  • 55