C# Enumerations


This entry is part 3 of 8 in the series C# Complex Types

An enum is a data type that only allows certain values for that piece of data. The stuff inside the brackets is called the enumerator list, and each item is an enumerator. The whole thing together is called an enumeration.

There is a discussion of enum in the book Illustrated C# 7: The C# Language Presented Clearly, Concisely, and Visually 5th Edition by Daniel Solis (Author), Cal Schrotenboer (Author) starting on page 304.

Example: Orientation

In the example, orientation is the name of the enum. Enums let you represent numbers with names. Sometimes it’s easier to work with numbers if you have names for them. You can assign numbers to the values in an enum and use the names to refer to them. That way, you don’t have a bunch of unexplained numbers floating around in your code. You can think of enums as a handy way to store lists of constants so you can refer to them by name. They’re great for keeping your code readable and making sure that you are always using the right variable names to access values that you use really frequently.

The downside to enums is that you need to cast them.

namespace Ch05Ex02
{  // define an enumeration type, in the namespace.
   // the underlying type is byte
    enum orientation : byte {                       
        north = 1, south = 2, east = 3, west = 4  }
    class Program {
        static void Main(string[] args)  {
            byte directionByte;
            string directionString;
            orientation myDirection = orientation.north;
            Console.WriteLine($"myDirection = {myDirection}"); // myDirection = north
            directionByte = (byte)myDirection;
            directionString = Convert.ToString(myDirection);  // myDirection type is orientation
            Console.WriteLine($"byte equivilant = {directionByte}");  // byte eqivilant = 1
            Console.WriteLine($"string equivilant = {directionString}");  // string equivilant = north
            // casting example shown below:
            byte myByte = 3;
            myDirection = (orientation)myByte;
            Console.WriteLine($"a byte with value 3 cast back to orientation type variable myDirection: {myDirection}");
            Console.ReadKey();
        }
        // even though the underlying type is byte, you still have to use (byte) cast to convert the 
        // value of myDirection into a byte type, as shown here: directionByte = (byte)myDirection;
        // because myDirection actually has a type of orientation, not byte.
    }
}
Series Navigation<< C# ArraysC# Enumerations Part 2 >>