Using Enumerations as Bit Flags

Enumerations are great. Bit flags are also great. How can we combine these two together?

That is, we want to do something like:


enum Fruits { Apple, Pear, Mango, Grapes }
Fruits f = Fruits.Apple | Fruits.Pear;
// pseudocode, bear with me
if (f has Apple) { ... }
if (f has Mango) { ... }

How?

In Any Version of .NET

The core step is really to assign 2^n integer values to each value of the enumeration, like so:


enum Fruits {
Apple = 1,
Pear = 2,
Mango = 4,
Grapes = 8
}

Note that adding the Flags attribute is not required. It’s optional. It just gives you nice ToString() representations.

All that’s left is checking the value.

How?

In .NET 4.0

.NET 4.0 has this down. It’s as simple as:


Fruits f = Fruits.Apple | Fruits.Mango;
if (f.HasFlag(Fruit.Apple)) { ... }

In Pre-4.0

Unfortunately, it’s not that easy before .NET 4.0, but it’s still quite easy. If you understand bit operators, then the same principle applies.

Look at it as binary. If apple = 1 and mango = 4, these in binary are:


Apple: 0x001
Mango: 0x100

Combining them (ANDing them) gives us 0x101, or a value of 5.

Reversing the value of five, how do we know if the third bit (for mango) is enabled? A simple AND operation:


Source: 0x101
Mango: 0x100
=============
Result: 0x100

Since AND requires both bits to be one for the resulting bit to be one, ANDing something to any value gives you that value back if the bit was set.

So we get:


if (f & Fruits.Mango == Fruits.Mango) { ... we have mangos ... }

Simple, right?

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, Silverlight, Web, Wndows Forms, WPF and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *