c# · level 3 · unit 1 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A class leaves a gap where the type goes.
You have used List<string> and Dictionary<string, int>. Those angle brackets are generics at work. Someone wrote the list class once, with a gap for the type. You fill the gap each time you make one, and C# checks every item against it.
Write your own by adding a after the class name: class Box<T>. Inside the class, T stands for whatever type the user picks. A Box<string> holds text, a Box<int> holds numbers, and one class serves both.
Put the wrong type in and the code never compiles, so the mistake cannot reach your users. No guessing, no surprises.
using System;
Box<string> lunch = new Box<string>("cheese sandwich");
Box<int> locker = new Box<int>(42);
string food = lunch.Item;
int number = locker.Item;
Console.WriteLine(food.ToUpper());
Console.WriteLine(number + 1);
class Box<T>
{
public T Item { get; }
public Box(T item) => Item = item;
} => Item = item; is a one-line body, the same as one statement inside braces.
guess first
Same class, two types. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
Box<int> score = new Box<int>(7);
Box<string> name = new Box<string>("Priya");
Console.WriteLine(name.Item + score.Item * 2);
class Box<T>
{
public T Item { get; }
public Box(T item) => Item = item;
}
your turn
Your turn. Build a box with two gaps.
A class can take two type parameters. On line 3, fill both type gaps with the same type, then give the Pair a matching value, like int and 12.
output
press run to see what happens
fix it
The box forgot its gap. Can you fix it?
output
press run to see what happens
- C# cannot find a type called
Ton lines 8 and 10. Where shouldTbe announced? - A type parameter is announced in angle brackets straight after the class name.
- Change line 6 to
class Box<T>, then run.
nailed it
your classes now work with any type. :D
- A type parameter like
Tis a gap for a type. - Fill the gap when you use the class:
Box<string>. - Wrong types are caught before the program ever runs.
new words in your collection
- generic
- type parameter
This lesson isn’t saved. A free account remembers every lesson you finish.