Generics
Generics make the type itself a parameter, so one class or method can be reused safely with int, string or any other type. Errors move from run time to compile time, casts disappear and value types are not boxed.
21.1 Why is it used?
- A class built on object accepts anything, so the compiler cannot stop a value of the wrong type going in.
- Every read from an object-based class needs a cast, and a wrong cast crashes at run time (InvalidCastException).
- Value types like int get boxed when stored as object: extra allocations and GC work.
- Writing IntShelf, StringShelf, ... separately is pure copy paste. Generics give one class for every type.
21.2 The bug: a class built on object
var prices = new Shelf();prices.Add(499);prices.Add("999");int total = (int)prices.Get(0) + (int)prices.Get(1);Console.WriteLine(total); class Shelf{ private object[] items = new object[10]; public int Count { get; private set; } public void Add(object item) => items[Count++] = item; public object Get(int i) => items[i];}$ dotnet run Shelf.csUnhandled exception.System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32'. at Program.<Main>$(String[] args) in Shelf.cs:line 4- The build passes because Add(object) accepts the string "999".
- The cast (int) on line 4 fails only when the program runs.
21.3 Generic class Shelf<T>
- T inside the angle brackets is a type parameter: a placeholder replaced by a real type when the class is used.
- The array is T[], Add takes a T and Get returns a T.
- new Shelf<int>() turns every T into int for that object, so no cast is needed.
var prices = new Shelf<int>();prices.Add(499);prices.Add(999); int total = prices.Get(0) + prices.Get(1);Console.WriteLine(total); class Shelf<T>{ private T[] items = new T[10]; public int Count { get; private set; } public void Add(T item) => items[Count++] = item; public T Get(int i) => items[i];}$ dotnet run Shelf.cs1498The same class with string: adding a number is now a compile error, caught in the editor instead of by users.
var names = new Shelf<string>();names.Add("Asha");names.Add(499);$ dotnet run Names.csNames.cs(3,11): error CS1503: Argument 1: cannot convert from 'int' to 'string'The build failed. Fix the build errors and run again.- Step 1
1.Write Shelf<T> once
- Step 2
2.Use it with a real type: Shelf<int>
- Step 3
3.Compile time: the compiler type-checks every call
- Step 4
4.Run time: value types like int get their own optimized code, no boxing
One code, every type, full type safety
21.4 Generic method + default
- Methods can be generic too: LastOrDefault<T> returns the last item or default for an empty array.
- Type inference: the call never writes <int> or <string>; the compiler works out T from the argument.
- default(T) is 0 for int, null for reference types, false for bool.
int[] scores = [72, 88, 95];string[] cities = ["Delhi", "Pune"]; Console.WriteLine(LastOrDefault(scores));Console.WriteLine(LastOrDefault(cities));Console.WriteLine(LastOrDefault(new int[0])); static T? LastOrDefault<T>(T[] items) => items.Length > 0 ? items[^1] : default;$ dotnet run Last.cs95Pune021.5 Constraints: rules on T
- Without a constraint the compiler only allows on T what every type has, so a > b does not compile.
- where T : IComparable<T> promises T can compare itself, so CompareTo can be called.
- int and string both implement IComparable<T>, so both calls work.
Console.WriteLine(Max(499, 999));Console.WriteLine(Max("Delhi", "Pune")); static T Max<T>(T a, T b) => a > b ? a : b;$ dotnet run Max.csMax.cs(5,8): error CS0019: Operator '>' cannot be applied to operands of type 'T' and 'T'The build failed. Fix the build errors and run again.static T Max<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b) >= 0 ? a : b;$ dotnet run Max.cs999Pune| Constraint | Meaning |
|---|---|
| where T : class | T must be a reference type (so null can be returned) |
| where T : struct | T must be a non-nullable value type |
| where T : new() | T must have a public parameterless constructor |
| where T : notnull | T cannot be a nullable type |
| where T : BaseClass / IInterface | T must derive from that class or implement that interface, so its members can be called |
21.6 Real-world example: Repository<T>
- where T : class means T is a reference type, so Find can return null.
- IEntity guarantees every T has an Id property, so item.Id compiles.
- The same class works for Product today and Order tomorrow.
class Repository<T> where T : class, IEntity{ private readonly List<T> items = []; public void Add(T item) => items.Add(item); public T? Find(int id) { foreach (var item in items) if (item.Id == id) return item; return null; }}$ dotnet run Repo.csKettle21.7 Closed types: is Shelf<int> the same type as Shelf<string>?
var a = new Shelf<int>();var b = new Shelf<string>();Console.WriteLine(a.GetType() == b.GetType());$ dotnet run Same.csFalse- Shelf<T> is a template (open generic type); every type argument creates a separate closed type.
- Static fields are therefore separate for Shelf<int> and Shelf<string>.
21.8 Comparison: object + cast vs generics
| Point | object + cast | Generics |
|---|---|---|
| Wrong type added | Builds, crashes at run time | Compile error (CS1503) |
| Reading a value | Cast on every read | No cast |
| Value types | Boxed | No boxing, own code per value type |
| Code reuse | One class but unsafe, or copy paste per type | One class, type safe |
21.9 Common mistakes
- Casting T inside a generic method, e.g. ((IEntity)item!).Id: new Repository<string>() builds and then throws InvalidCastException.
- Fix: add where T : IEntity; now item.Id needs no cast and Repository<string> is a compile error (CS0311).
- Rule: if you see a cast in generic code, replace it with a constraint.
- Myth: generics become object underneath like Java type erasure. In C# the runtime knows the real type and List<int> does no boxing.
- Step 1
1.Generic code needs item.Id
- Step 2
2.Wrong: cast ((IEntity)item!).Id
- Step 3
3.new Repository<string>() builds, then InvalidCastException at run time
- Step 4
4.Right: class Repository<T> where T : IEntity
- Step 5
5.item.Id compiles; Repository<string> fails at build with CS0311
A constraint moves the error from run time to compile time
21.10 Rules for generics
- Use generics instead of object and casts, so errors are caught at compile time.
- Name type parameters T, or meaningfully: TKey, TValue.
- Add only the constraints the code really needs.
- Check for a ready .NET generic type (List<T>, Dictionary<TKey,TValue>, Task<T>) before writing your own.
21.11 Interview tips
- Generics make the type a parameter, so one class or method is reused type safely with many types.
- Benefits: no casts, errors at compile time, no boxing for value types.
- Constraints (class, struct, new(), notnull, base class, interface) put rules on T so its members can be called safely.
- C# generics are reified, not erased: Shelf<int> and Shelf<string> are different closed types (GetType() comparison is False).