Lesson 39 +10 XP

C# Enums

C# Enums

An enum (enumeration) is a special class that represents a group of constants - named values that can't change.

Creating an enum

enum Level
{
  Low,
  Medium,
  High
}

Using an enum

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

This prints Medium.

Inside a switch

Enums are perfect for switch statements:

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;
}

Enum values are numbers

By default, the first item has the value 0, the second 1, and so on. You can assign your own numbers:

enum Months
{
  January = 1,
  February = 2,
  March = 3,
  April = 4
}
Console.WriteLine((int) Months.April);   // 4

Cast to int to get the numeric value.

Why use enums?

  • Make code readable - Level.Medium is clearer than 1.
  • Prevent typos - only the defined names are allowed.
  • Keep related constants together.

TL;DR

  • enum defines a group of named constants.
  • Items are numbers by default (0, 1, 2...).
  • Assign custom values with =.
  • Cast with (int) to get the numeric value.