RJP
RJP

Reputation: 4116

Bit flags always including 0 value

So I came accross this code:

[Flags]
public enum Options
{
    NA = 0,
    OptionA = 1,
    OptionB = 2,
    OptionC = 4
}

Now, technically 'NA' is invalid, if the user doesn't want to select any Options, they just wont select any, and it will get saves to a nullable int. There is no "None" option. However, any time the user selects Options A-C, NA will always get added as well. If I change NA = 1, then OptionC = 8, everything works well. That portion makes sense. But how come NA will always be included in the user's option list if NA = 0?

Edit:

To clear some things up, NA is exclusive, but if I where to select OptionB, then when I view the selected Options, it will show I selected NA and OptionB.

Upvotes: 0

Views: 753

Answers (2)

Matt Burland
Matt Burland

Reputation: 45135

If you are going to use an enum with the Flags attribute, then only use the value of 0 if you have an option that is exclusive of all other options (like None, for example). Then you test it with:

if (myOptions == Options.Na)

Testing with:

if ((myOptions & Options.Na) == Options.Na)

Will, of course, always return true.

Now the name Na suggest that it is exclusive of all the other options, so what's the problem?

Upvotes: 2

Joachim Isaksson
Joachim Isaksson

Reputation: 180897

When you're adding Flags as an attribute on an enum, and a value that is 0, it will always be included if you use & to filter the values out.

That is due to that all required bits (none in that case) are always set.

Upvotes: 3

Related Questions