← C# from Scratch Lesson 36 of 39 · 10 XP

Enumerations (enum)

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

An enum is a set of named constants. Instead of "magic" numbers like state == 2, we write state == State.Running:

enum Direction { North, East, South, West }   // 0, 1, 2, 3

Direction d = Direction.East;
Console.WriteLine(d);              // East — the name is printed
Console.WriteLine((int)d);         // 1
d = (Direction)(((int)d + 1) % 4); // South — a clockwise turn
Direction e = Enum.Parse<Direction>("West");

switch (d)
{
    case Direction.North: y++; break;
    …
}
  • values can be set explicitly: enum Level { Easy = 1, Hard = 10 };
  • Enum.GetValues<Direction>() gives all the values, handy for loops.

Task. A robot stands at (0, 0) facing North (north is y+1, east is x+1). The commands come on one line: L — turn left, R — turn right, F — one step forward. Print x y direction.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.