Codiqo

Learn C# · lesson 54 of 61 · about 8 minutes

enum

Name a fixed set of choices so the compiler can check you only use real ones.

What you'll learn

  • Define an enum and use its values
  • Switch on an enum
  • Convert between enums, numbers and text

At the dragon's lair

The trap is made, and the hero stands at the mouth of the dragon's lair. Before going in, the hero runs through the combo again, but this dragon breathes fire: a slash still does 4, fire does nothing at all, and ice does 10. The moves were typed as words like slash, and a word can be anything. This unit turns them into an enum, Attack, which has just three values, so DragonDamage can switch on them: Slash at the dragon: 4, Fire at the dragon: 0, and then Combo at the dragon: 8 damage.

A type with a fixed set of values

Some values can only be one of a few choices: a traffic light is red, amber or green. Strings like "red" can be misspelt, and nothing stops "purple".

An enum lists every allowed value: enum Light { Red, Amber, Green }. A Light variable holds one of them, and a typo like Light.Rde won't compile. In a file with top-level statements, enums go after the main code, like classes.

A switch expression on an enum

Light l = Light.Red;
for (int i = 0; i < 4; i++)
{
    Console.Write($"{l} ");
    l = Next(l);
}
Console.WriteLine();

static Light Next(Light l) => l switch
{
    Light.Red => Light.Green,
    Light.Green => Light.Amber,
    _ => Light.Red,
};

enum Light { Red, Amber, Green }

Output

Red Green Amber Red

Numbers and text

Underneath, each value is a number counting from 0, and (int)l gives it. Enum.Parse<Light>("Green") turns text into the value, Enum.TryParse does it safely, and Enum.GetValues<Light>() lists every value.

Converting

foreach (Size s in Enum.GetValues<Size>()) Console.Write($"{(int)s}:{s} ");
Console.WriteLine();

Size chosen = Enum.Parse<Size>("Large");
Console.WriteLine(chosen == Size.Large);
Console.WriteLine(Enum.TryParse("huge", out Size _));

enum Size { Small, Medium, Large }

Output

0:Small 1:Medium 2:Large
True
False

From the combo's words to attacks

The combo kept only the moves it knows, all in lower case. Enum.Parse<Attack>(m, ignoreCase: true) turns each one into an Attack, so slash becomes Attack.Slash; without ignoreCase it would only match Slash exactly and throw for slash. known.Select(...) does that for every move at once. From then on DragonDamage switches on the enum value instead of comparing strings, and a typo like Attack.Ise won't even compile. Printing an Attack shows its name, so Slash at the dragon: 4 needs no extra work.

Tip

C# enum values are usually written in PascalCase, like Light.Red, the same as other names in C#.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.