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 ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.