How to use enums as bit flags

This took me a few minutes to find, so I thought I’d write it down here. Normally, you can only use an enum to represent one value. But what if you want to use an enum to represent several values? Here’s how you’d do it. First, define an enum – add the "[Flags]" attribute – and give every value a unique binary representation (1, 2, 4, 8, 16, 32, 64, 128, 256, etc)

[Flags]

private enum Colors

{

    Red = 1,

    Blue = 2,

    Green = 4,

    Yellow = 8

}

Then, to use this bitmask, you could do code such as this to assign – then test the values:

Colors favoriteColors;

favoriteColors = Colors.Blue | Colors.Red;

 

if ( (favoriteColors & Colors.Red) == Colors.Red )

    MessageBox.Show("Likes red!");

 

if ( (favoriteColors & Colors.Blue) == Colors.Blue )

    MessageBox.Show("Likes blue!");

 

if ( (favoriteColors & Colors.Green) == Colors.Green )

    MessageBox.Show("Likes green!");

 

if ( (favoriteColors & Colors.Yellow) == Colors.Yellow )

    MessageBox.Show("Likes yellow!");

 

Posted in General, Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Archives
Categories

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 5 other followers

%d bloggers like this: