C# › Generics

What are generics in C#, and what specific problems do they solve compared to writing type-specific code?

Intermediate

Answer

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 ArrayList
Real-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.

Common follow-ups: How do generic constraints (where T : IComparable<T>) restrict what types can be used?;Why do generic collections like List<T> outperform their non-generic predecessors like ArrayList?