C# Enums

An enum is a special "class" that represents a group of constants (unchangeable/read-only variables).

To create an enum, use the enum keyword (instead of a class or visual interface), and comma-separate objects:

Example
enum Level 
            {
              Low,
              Medium,
              High
            }
            

Level myVar = Level.Medium;
            Console.WriteLine(myVar);

Enum inside a Class

You can also have an enum within the class:

Example
class Program
            {
              enum Level
              {
                Low,
                Medium,
                High
              }
              static void Main(string[] args)
              {
                Level myVar = Level.Medium;
                Console.WriteLine(myVar);
              }
            }

Enum Values

By default, the first enum item has a value of 0. The second one has a value of 1, and so on.

To get the full value of an item, you must explicitly convert the item into an int:

Example
enum Months
            {
              January,    // 0
              February,   // 1
              March,      // 2
              April,      // 3
              May,        // 4
              June,       // 5
              July        // 6
            }
            
            static void Main(string[] args)
            {
              int myNum = (int) Months.April;
              Console.WriteLine(myNum);
            }

You can also share your enum values, and the following items will update the number accordingly:

Example
enum Months
            {
              January,    // 0
              February,   // 1
              March=6,    // 6
              April,      // 7
              May,        // 8
              June,       // 9
              July        // 10
            }
            
            static void Main(string[] args)
            {
              int myNum = (int) Months.April;
              Console.WriteLine(myNum);
            }

Enum in a Switch Statement

Enums are commonly used in switch statements to check the corresponding prices:

Example
enum Level 
            {
              Low,
              Medium,
              High
            }
            
            static void Main(string[] args) 
            {
              Level myVar = Level.Medium;
              switch(myVar) 
              {
                case Level.Low:
                  Console.WriteLine("Low level");
                  break;
                case Level.Medium:
                   Console.WriteLine("Medium level");
                  break;
                case Level.High:
                  Console.WriteLine("High level");
                  break;
              }
            }