ASP.NET Hosting

Bitfield enums and the Flags attribute

You can work with enum as bitfields if you use powers of 2 for the values.
For example, if you have an enum like this one:

enum Abcd {A = 1, B = 2, C = 4, D = 8}

you can use bitwise operations such as OR to combine values.

Maybe you noticed the Flags attribute which is part of the framework. But, what is its purpose, you may ask, since we can use enums as bitfields even if we do not add the Flags attribute. Well, this attribute is used for the ToString method for example. If you use the Flags attribute as follows:

[Flags]
enum Abcd {A = 1, B = 2, C = 4, D = 8}

then calling the ToString method on a variable of type Abcd containing A and C (myvar = Abcd.A | Abcd.C), the result will be "A, C". This is used by Visual Studio to display the value of bitfield properties, for example.

Conclusion, if you want to use bitfield enums, use the Flags attribute and powers of 2.

Note: VB.NET syntax:

<Flags()> _
Enum Abcd
  A = 1
  B = 2
  C = 4 
  D = 8
End Enum

1 Comment

  • It is often preferable to use the bitwise shift operator for populating bitfields, as it makes things a bit more readable.

    [Flags]

    public enum Day

    {

    &nbsp; &nbsp;Sunday &nbsp; &nbsp; &nbsp;= 1 &lt;&lt; 6

    &nbsp; &nbsp;,Monday &nbsp; &nbsp; = 1 &lt;&lt; 5

    &nbsp; &nbsp;,Tuesday &nbsp; &nbsp;= 1 &lt;&lt; 4

    &nbsp; &nbsp;,Wednesday &nbsp;= 1 &lt;&lt; 3

    &nbsp; &nbsp;,Thursday &nbsp; = 1 &lt;&lt; 2

    &nbsp; &nbsp;,Friday &nbsp; &nbsp; = 1 &lt;&lt; 1

    &nbsp; &nbsp;,Saturday &nbsp; = 1 &lt;&lt; 0

    }

Comments have been disabled for this content.