Fabrice's weblog

Tools and Source

News

My .NET Toolbox
An error occured. See the script errors signaled by your web browser.
No tools selected yet
.NET tools by SharpToolbox.com

Read sample chapters or buy LINQ in Action now!
Our LINQ book is also available on AMAZON

.NET jobs

Emplois .NET

transatlantys hot news

Contact

Me

Others

Selected content

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

Posted: Dec 18 2003, 04:38 PM by Fabrice Marguerie | with 2 comment(s)
Filed under:

Comments

M. Keith Warren said:

Awesome Tip!
# December 18, 2003 11:57 AM

Chris said:

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

{

   Sunday      = 1 << 6

   ,Monday     = 1 << 5

   ,Tuesday    = 1 << 4

   ,Wednesday  = 1 << 3

   ,Thursday   = 1 << 2

   ,Friday     = 1 << 1

   ,Saturday   = 1 << 0

}

# January 4, 2009 7:34 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)