BLOG.CSHARPHELPER.COM: Make and use bitmasks in C#
Make and use bitmasks in C#
The example Understand how to use bit masks in C# explains how to use bitmasks. To make a bitmask, simply create an enum and give it the Flags attribute as in the following code.
If you do not specify numeric values for the enumerated names, the enum gives them the values 1, 2, 3, and so forth. If you want all of the names to represent distinct values, you should set them equal to different powers of 2 as in the preceding code. Then you can combine them in any combination by using bitwise operators.
You can also define combined values if you like. For example, you could use the following code to create a value that includes both Value1 and Value2.
Value3and5 = Value3 | Value5,
The enum doesn't automatically make the values powers of two so what do you get by using the Flags attribute? The attribute tells designers and other programs that the enum is intended to be a bitmask. More directly useful, it also allows the enum how to handle combined values when you invoke its ToString method. For example, consider the following code.
Each of these statements makes a value that combines two other values. The code's definition of NormalEnum is the same as the definition of BitmaskEnum except it doesn't use the Flags attribute so both of the combined values are 1 | 2 = 0001 | 0010 = 0011 = 3.
The program displays various values in its TextBox when it starts. The following lines show how it displays the values of these two variables.
If you look closely at the picture, you'll see that ToString returns "3" for the normal enum value and "Value1, Value2" for the enum declared with the Flags attribute.
Comments