Learn C# · lesson 55 of 61 · about 9 minutes
Generic Classes
Write a class once and use it for ints, strings or anything else, like List<T> does.
What you'll learn
- Write a generic class with <T>
- Create objects with a chosen type
- Use more than one type parameter
The narrow tunnel
The way into the lair is a tunnel too narrow for the whole bag. The hero takes a satchel with room for 3 things, and a belt with room for 2 attacks to have ready. The satchel holds strings and the belt holds Attack values, but both work the same way: put things in until there's no room. Instead of writing that class twice, this lesson writes it once as Satchel<T>, and makes a Satchel<string> with room for 3 and a Satchel<Attack> with room for 2. With the bag from the chest that's No room for the rope, No room for the torch, Satchel: bread, gem, key and Belt: Slash, Fire.
You've been using generics all along
List<string> and Dictionary<string, int> are generic classes: the type in angle brackets is filled in when you use them, and the compiler makes sure only that type goes in.
You can write your own. class Box<T> makes T a type parameter, a stand-in for whatever type each Box is made with: Box<int>, Box<string>.
A box for anything
var number = new Box<int>(41);
var word = new Box<string>("phoebe");
number.Value++;
Console.WriteLine($"{number.Value} {word.Value.ToUpper()}");
class Box<T>(T value)
{
public T Value { get; set; } = value;
}Output
42 PHOEBETwo type parameters
A class can have several: class Pair<TFirst, TSecond>. Each object chooses both. By convention type parameters start with T, either just T or a name like TKey.
A pair of two types
var p = new Pair<string, int>("lives", 3);
var q = p.Swapped();
Console.WriteLine($"{p.First} {p.Second} / {q.First} {q.Second}");
class Pair<TFirst, TSecond>(TFirst first, TSecond second)
{
public TFirst First { get; } = first;
public TSecond Second { get; } = second;
public Pair<TSecond, TFirst> Swapped() => new(Second, First);
}Output
lives 3 / 3 livesOne class, two satchels
Inside Satchel<T>, nothing depends on what T is. Put(T item) only counts what's already there and adds the item, and ToString joins the items with string.Join, which calls each one's own ToString, so strings print as themselves and attacks print as their names. Put gives back false when the satchel is full, so the main code can say what was left behind. The room comes in through the constructor, class Satchel<T>(int room), so each satchel can be a different size.
Tip
Unlike Java, C# generics work with int, double and bool directly: List<int> really holds ints.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.