BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

Bit Field Enumerations

When you need to store multiple Boolean statuses for a single item, you may elect to place each on/off attribute into a bit field. If you use an enumeration marked with the FlagsAttribute class, the .NET framework will assist with some of the operations.

Combining Bits

Variables can be declared using the bit field enumerated type. To assign the default value or a single bit, the variable can simply be assigned one of the constant values. Where more than one bit must be set, the integer value can be used but it is more descriptive to use the logical OR operator (|) and the names of the flags.

PrinterStatus ok = PrinterStatus.OK;
PrinterStatus offline = PrinterStatus.OffLine;
PrinterStatus multi = PrinterStatus.PaperJam | PrinterStatus.TonerExhausted;

Reading Individual Flags

It is important to be able to isolate a single flag and determine its value. This can be achieved using the logical AND (&) operator. The sample code below shows how to isolate the paper tray empty and paper jam error statuses. If the flag is set, the resultant value will be equal to the flag's enumeration constant. If not set, the resultant value will be zero (PrinterStatus.OK).

PrinterStatus status = PrinterStatus.TonerExhausted | PrinterStatus.PaperJam;

PrinterStatus offline = status & PrinterStatus.OffLine;  // PrinterStatus.OK
PrinterStatus jammed = status & PrinterStatus.PaperJam;  // PrinterStatus.PaperJam
16 March 2008