Reputation: 15200
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.
Upvotes: 0
Views: 570
Reputation: 6554
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.
Upvotes: 1
Reputation: 2142
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,
}
Upvotes: 5
Reputation: 3951
You enum is numbered consecutively starting at 0. To use bit flags, you will need to manually number them as powers of 2.
Upvotes: 2