Generics Explained
Generics let you parameterize a class, interface, method, or delegate with a type that is supplied by the caller, rather than hard-coding a specific type. Before generics (pre-C# 2.0), general-purpose collections had to operate on object, which meant boxing value types on every insertion, unboxing on every read, and no compile-time guarantee that a collection actually contained the type you expected — errors surfaced only at runtime as InvalidCastException. List<T> replaced the old non-generic ArrayList precisely to solve this: List<int> stores int values directly with no boxing, and the compiler enforces that only int values can be added, catching type mistakes at compile time instead of runtime.
Cricket analogy: Before dedicated bowling machines, coaches used a generic 'ball feeder' that could jam or misfeed any object; a machine calibrated specifically for cricket balls (like List<int> for int) catches a wrong-sized ball at load time instead of mid-delivery.
Generic classes and methods
A generic type is declared with one or more type parameters in angle brackets, conventionally named T for a single parameter or descriptively (TKey, TValue, TResult) for multiple. Generic methods can introduce their own type parameters independent of any containing type's parameters, and the compiler can usually infer them from the arguments passed, so callers rarely need to specify them explicitly.
Cricket analogy: A scouting template with a slot named 'Player' works for any sport, but a cricket-specific template with slots named 'Batter' and 'Bowler' (like TKey, TValue) is clearer — and a good scout can usually tell which role a recruit fits without being told explicitly.
public class Repository<TEntity, TId> where TEntity : class, IIdentifiable<TId>
{
private readonly Dictionary<TId, TEntity> _store = new();
public void Save(TEntity entity) => _store[entity.Id] = entity;
public TEntity? Find(TId id) =>
_store.TryGetValue(id, out var entity) ? entity : null;
public IEnumerable<TEntity> All() => _store.Values;
}
public interface IIdentifiable<TId>
{
TId Id { get; }
}
public record Product(int Id, string Name) : IIdentifiable<int>;
// Generic method with inferred type argument.
static TResult ExecuteWithLogging<TResult>(Func<TResult> operation, string label)
{
Console.WriteLine($"Starting: {label}");
var result = operation();
Console.WriteLine($"Finished: {label}");
return result;
}
var repo = new Repository<Product, int>();
repo.Save(new Product(1, "Widget"));
var found = ExecuteWithLogging(() => repo.Find(1), "lookup");Constraints
Type parameter constraints (where T : ...) restrict what types can be substituted, in exchange for letting the compiler assume more about T inside the generic code. Common constraints include where T : class (reference type), where T : struct (value type), where T : new() (must have a public parameterless constructor), where T : BaseClass, where T : ISomeInterface, and where T : notnull. C# 11 added static abstract interface members, which combined with generic constraints let you write generic math code that calls static operators (+, *, comparison) directly on the constrained type parameter.
Cricket analogy: A team's overseas-signing rule (where T : Foreign) restricts who can be recruited, but lets the selectors assume every signing needs a visa; similarly, a rule requiring 'must have international caps' (where T : Capped) lets management skip a fitness re-test.
Generics in C# are reified at runtime via the CLR, unlike Java's type erasure. This means typeof(List<int>) != typeof(List<string>), and reflection can inspect the actual type arguments a generic instance was constructed with at runtime — a capability Java generics fundamentally cannot offer because Java erases generic type information during compilation.
A common misconception is that generics automatically make code fast for all type arguments equally. For value types, the CLR generates a specialized native implementation per value-type argument (avoiding boxing), but for reference types, all reference-type instantiations of a generic share a single compiled implementation at the CLR level, since references are uniformly sized. This is an implementation detail, not something you typically need to optimize around, but it explains why List<int> and List<string> behave identically in terms of boxing avoidance despite the sharing difference under the hood.
Variance in generic interfaces
Generic interfaces and delegates can declare variance on their type parameters using out (covariant, safe for return-only positions like IEnumerable<out T>) or in (contravariant, safe for parameter-only positions like IComparer<in T>). Covariance lets IEnumerable<string> be used where IEnumerable<object> is expected; contravariance lets an IComparer<object> be used where IComparer<string> is expected. Variance only applies to interfaces and delegates, never to generic classes, because classes can have both input and output positions (fields, settable properties) that would make it unsafe.
Cricket analogy: A 'young talent scout' role can safely be filled by someone scouting only U19 players (covariant, out), usable wherever a general scout is needed; but a 'team disciplinarian' role needing to handle any player (contravariant, in) can't be limited to just U19s — and a fixed squad roster can't flex this way at all, since it both fields and benches players.
- Generics let types and methods be parameterized by a caller-supplied type, giving compile-time type safety without boxing for value types.
- Generic type parameters are conventionally named T, TKey, TValue, TResult, etc., and can be inferred by the compiler in most method calls.
- Constraints (
where T : ...) restrict permissible type arguments in exchange for the compiler assuming more capabilities about T. - C# generics are reified at runtime by the CLR, unlike Java's type-erased generics, enabling accurate runtime type inspection.
- Variance (
out/in) applies only to interfaces and delegates, allowing safe substitutability like IEnumerable<string> for IEnumerable<object>. - Value-type generic instantiations get specialized native code per type; reference-type instantiations share a single compiled implementation.
Practice what you learned
1. What was the primary problem generics solved compared to using object-based collections like the old ArrayList?
2. What does the constraint `where T : new()` require of the type argument?
3. How do C# generics differ fundamentally from Java generics at runtime?
4. Which type parameter variance annotation allows IEnumerable<string> to be used wherever IEnumerable<object> is expected?
5. Can generic variance (in/out) be applied to a generic class?
Was this page helpful?
You May Also Like
Collection Interfaces
Survey the layered hierarchy of IEnumerable, ICollection, IList, and their read-only and generic variants that unify how .NET collections are consumed.
Arrays and Lists
Compare C#'s fixed-size arrays with the dynamically resizable List<T>, covering allocation, performance characteristics, and when to reach for each.
Dictionaries and Sets
Learn how Dictionary<TKey,TValue> and HashSet<T> use hashing for near-constant-time lookups, and how to use them correctly with custom key types.
Interfaces in C#
Understand interfaces as pure behavioral contracts that any type can implement, including default interface methods, explicit implementation, and multiple interface inheritance.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics