C Sharp Flags

From Leo's Notes
Revision as of 19:05, 9 December 2012 by Leo (talk | contribs) (Created page with "== Defining Flags == [Flags] public enum State { Idle = 0x01, Available = 0x02, InService = 0x04, Accelerating = 0x08, Decelerating = 0x10, Sto...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
This page was last edited on 9 December 2012, at 19:05.

Defining Flags

[Flags]
public enum  State {
   Idle = 0x01,
   Available = 0x02,
   InService = 0x04,
   
   Accelerating = 0x08,
   Decelerating = 0x10,
   Stopped = 0x20,
}

Notice that the flags are given values of powers of two.

Operations

Setting a Flag

Use the bit-wise OR operation to set (add) a flag.

State state = State.Available;
state = state | State.Stopped;

state now has both Available and Stopped. The actual value of state</state> is 0x22 (from 0x02 + 0x22)

Removing a Flag

Use the bit-wise XOR (^) operation to unset (remove) a flag.

State state = State.Available | State.Stopped;
state = state ^ State.Available;
state = state ^ State.Stopped;
state = state | State.InService;

state is now InService. The actual value of state</state> is 0x04.


Checking

Use the bit-wise AND operation to do checking.

State state = State.Available | State.Stopped;

if (state & State.Idle == State.Idle) {
   // This will fail as state is set to Available and Stopped.
}