enum
First, we tried to use Constants to distinguish our "Magic Numbers"
const int NOT_STARTED = 0;
const int STARTED = 1;
// ...
const int FINISHED = 5;
But it got complicated as we needed more of them...
const int SHIPMENT_STARTED = 1;
// ...
const int RETURN_MINOR_DAMAGE = 1;
enum
"Magic Numbers" are an imperfect solution
enum
- A Better Approachpublic enum ReturnState { NoDamage, MinorDamage, SignificantDamage }
public enum RepairStatus { NotStarted, Started, /*...*/ Finished}
Enumerations allow us to
ReturnState.NoDamage
is different from ReturnState.MinorDamage
ReturnState.Started
would be a compiler errorpublic enum ReturnState { NoDamage, MinorDamage, SignificantDamage }
ReturnState
is the data typeNoDamage
, MinorDamage
and SignificantDamage
are distinct valuesReturnState shipmentItem = ReturnState.NoDamage;
shipmentItem
is a variable of type ReturnState
with an initial value of NoDamage
By default, enum values
int
values under-the-hoodpublic enum ReturnState
{
NoDamage, // = 0
MinorDamage, // = 1
SignificantDamage // = 2
}
We can set the underlying values and even change the underlying data type to any whole-number data type (int
, short
, long
).
public enum DayOfWeek : short
{
Unknown = -1,
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
}
[Flags]
public enum WeaponStatus
{ // Binary Representation
Offline = 0, // 00000000
Online = 1, // 00000001
Armed = 2, // 00000010
Firing = 4, // 00000100
Damaged = 8 // 00001000
}
WeaponStatus torpedo = WeaponStatus.Armed | WeaponStatus.Online; // bitwise OR
// ...
if(torpedo.HasFlag(WeaponStatus.Online))
// ...
switch
StatementsEnumerations are handy in simple switch
statements.
switch(status)
{
case ReturnState.NoDamage;
// ...
break;
case ReturnState.MinorDamage;
// ...
break;
case ReturnState.SignificantDamage;
// ...
break;
}
[Flags]
)void Main() { WeaponStatus torpedo = WeaponStatus.Firing | WeaponStatus.Online; if(torpedo == WeaponStatus.FireInTheHole) Console.WriteLine(torpedo); if(torpedo.HasFlag(WeaponStatus.Online)) Console.WriteLine("Phasers Ready"); torpedo = WeaponStatus.Armed | WeaponStatus.Damaged | WeaponStatus.Firing; if(torpedo == WeaponStatus.FireInTheHole) Console.WriteLine("EVACUATE"); } // Define other methods, classes and namespaces here [Flags] public enum WeaponStatus { // Binary Representation Offline = 0, // 00000000 Online = 1, // 00000001 Armed = 2, // 00000011 Firing = 4, // 00000101 Damaged = 8, // 00001000 FireInTheHole = 14 // 00001110 }