C# › Generics
What are generics in C#, and what specific problems do they solve compared to writing type-specific code?
IntermediateAnswer
Generics let you define a class, method, or interface with a placeholder type parameter (like <T>) that's specified when the type is actually used, avoiding the need to write near-identical code for every different data type -- beyond reducing duplication, generics provide genuine compile-time type safety (the compiler rejects an incompatible type at the call site) and better performance than the older, pre-generics approach of using object and relying on boxing/unboxing or unsafe casts.
// Without generics: separate overloads needed per type
public void Print(int value) => Console.WriteLine(value);
public void Print(string value) => Console.WriteLine(value);
// With generics: one method, any type, still fully type-checked
public void Print<T>(T value) => Console.WriteLine(value);
List<int> numbers = new(); // type-safe: only accepts int, unlike the old non-generic ArrayListReal-world example A generic Repository<T> base class implements common CRUD operations (Add, GetById, Delete) once, reused across UserRepository, ProductRepository, and every other entity-specific repository in the application without duplicating the same logic per entity type.