20.14. Determining Whether One or More Enumeration Flags Are Set
Problem
You need to determine if a variable of an enumeration type, consisting of bit flags, contains one or more specific flags. For example, given the following enumeration Language:
[Flags]
enum Language
{
CSharp = 0x0001, VBNET = 0x0002, VB6 = 0x0004, Cpp = 0x0008
}determine, using Boolean logic, if the variable lang in the following line of code contains a language such as Language.CSharp and/or Language.Cpp:
Language lang = Language.CSharp | Language.VBNET;
Solution
To determine if a variable contains a single bit flag that is set, use the following conditional:
if((lang & Language.CSharp) == Language.CSharp)
{
// Lang contains at least Language.CSharp.
}To determine if a variable exclusively contains a single bit flag that is set, use the following conditional:
if(lang == Language.CSharp)
{
// lang contains only the Language.CSharp
}To determine if a variable contains a set of bit flags that are all set, use the following conditional:
if((lang & (Language.CSharp | Language.VBNET)) ==
(Language.CSharp | Language.VBNET))
{
// lang contains at least Language.CSharp and Language.VBNET.
}To determine if a variable exclusively contains a set of bit flags that are all set, use the following conditional:
if((lang | (Language.CSharp | Language.VBNET)) ==
(Language.CSharp | Language.VBNET))
{
// lang contains only the Language.CSharp and Language.VBNET.
}Discussion
When enumerations are used as bit flags and are marked with ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access