×

c# · level 2 · unit 4 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An names every choice you allow.

Some choices come from a short, fixed list: small, medium or large. Storing them as text invites typos like "meduim". An enum names every allowed choice once: enum Size { Small, Medium, Large }. Like a class, it goes below the main lines.

Write a choice as Size.Medium and compare with ==. C# checks the names before running, so Size.Huge is refused with CS0117. Printing an enum shows its name, and (int) in front reveals its number, counting from 0.

Typed text becomes an enum with : Enum.Parse<Size>("Large"). Text that matches no name stops the program with ArgumentException.

using System;

Size order = Size.Medium;
Console.WriteLine($"You picked {order}");
Console.WriteLine(order == Size.Large);
Console.WriteLine((int)order);
Size typed = Enum.Parse<Size>("Large");
Console.WriteLine($"Upgraded to {typed}");

enum Size { Small, Medium, Large }

Enum choices start with a capital letter, like class names.