WTF is an Enum?
I’m a data-person but I like to change it up every now and then jump into some real code. I was dabbling in C# last week and was looking into Enums. I had heard about them a lot but never REALLY knew what they were or how they were constructed, so I forced myself to figure out WTF they were.
In computer programming, an enumerated type (also called enumeration or enum) is a data type consisting of a set of named values called elements, members or enumerators of the type. The enumerator names are usually identifiers that behave as constants in the language. A variable that has been declared as having an enumerated type can be assigned any of the enumerators as a value.
For example, the four suits in a deck of playing cards may be four enumerators named CLUB, DIAMOND, HEART, SPADE, belonging to an enumerated type named suits. If a variable V is declared having suits as its data type, one can assign any of those four values to it.
The enumerators are necessarily distinct, even though some languages may allow the same enumerator to be listed twice in the type’s declaration. The enumerators need not be complete or compatible in any sense. For example, an enumerated type called color may be defined to consist of the enumerators RED, GREEN, ZEBRA, and MISSING. In some languages, the declaration of an enumerated type also defines an ordering of its members.
Some enumerator types may be built into the language. The Boolean type, for example is often a pre-defined enumeration of the values FALSE and TRUE. Many languages allow the user to define new enumerated types.
Here’s a quick look at how to create an Enum and how to use them.
using System;
// declares the enum
public enum Volume
{
Low,
Medium,
High
}
// demonstrates how to use the enum
class EnumSwitch
{
static void Main()
{
// create and initialize
// instance of enum type
Volume myVolume = Volume.Medium;
// make decision based
// on enum value
switch (myVolume)
{
case Volume.Low:
Console.WriteLine("The volume has been turned Down.");
break;
case Volume.Medium:
Console.WriteLine("The volume is in the middle.");
break;
case Volume.High:
Console.WriteLine("The volume has been turned up.");
break;
}
Console.ReadLine();
}
}
Recent Buzz