×

c# · level 3 · unit 1 · 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

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.