C# Tutorial: Generics
Generic classes, methods, constraints, and covariance/contravariance.
Type-safe code for any type
Generics let you write code that works for multiple types without sacrificing type safety.
No boxing, no casting — the compiler generates type-specific code at JIT time.
What you'll learn in this C# generics tutorial
This interactive C# tutorial has 8 hands-on exercises. Estimated time: 18 minutes.
- Generic method — A generic method uses `<T>` as a placeholder type.
- Generic class — A generic class holds data of any type while remaining type-safe.
- Generic Stack — Implement a stack that works for any element type.
- Constraints (where) — `where T : ...` constrains what types can be used.
- Multiple type parameters — Generics can have multiple type parameters.
- default(T) — `default(T)` returns the default value for any type (null for reference types, 0 for numerics).
- Generic repository pattern — Generics are the foundation of most framework patterns, like the repository.
- Covariance with out — `IEnumerable<out T>` allows assigning a List<Dog> to IEnumerable<Animal>.
C# Generics concepts covered
- Type-safe code for any type