Generics
Box<T> is a generic class — T is a placeholder filled in with a real type wherever Box is used. Box<string> and a hypothetical Box<int> are both valid, type-safe instantiations of the exact same class, with the compiler catching any type mismatch at the call site.
Main.cs
Try it yourself →using System;
class Box<T> {
private T value;
public Box(T value) { this.value = value; }
public T GetValue() { return value; }
}
class Program {
static void Main() {
Box<string> box = new Box<string>("hello");
Console.WriteLine(box.GetValue());
}
}Output
hello
Next: collections and LINQ — querying collections with Where and Select, C#'s signature feature with no real equivalent anywhere else on this site.
Practice exercise
Define a generic class Box<T> with a value field and a GetValue() method. Create a Box<string> holding "hello", then print its value.