c# · level 2 · unit 4 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Midweek already? What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
Day today = Day.Wed;
Console.WriteLine($"{today} is day {(int)today}");
enum Day { Mon, Tue, Wed, Thu, Fri }
your turn
Your turn. Add a drink to the menu.
Add a third drink to the enum on line 6. Then order any drink on line 3 and press run to see its number.
output
press run to see what happens
fix it
The pet picker will not pick. Fix it!
output
press run to see what happens
- C# stops with
ArgumentExceptionon line 4. Compare the typed text with the names in the enum on line 7. Enum.Parsematches names exactly, capitals included.catis notCat.- Change line 3 to
string typed = "Cat";, then press run.
nailed it
your choices have names now. :D
- An enum lists every allowed choice.
- Printing shows the name,
(int)shows the number. Enum.Parseturns matching text into a choice.
new words in your collection
- enum
- Enum.Parse
This lesson isn’t saved. A free account remembers every lesson you finish.