Back to results for “Structs”
C# › Generics

What problem do generics solve compared to writing a method or class that accepts 'object'?

Beginner

Answer

Using 'object' loses type safety entirely — you'd need to cast every value back to its real type manually, risking runtime InvalidCastExceptions, and value types get boxed. Generics let a class or method work with MULTIPLE specific types while the compiler enforces type safety and avoids unnecessary boxing, checked entirely at compile time.
// Using object: loses type safety, requires casting, boxes value types
public object GetFirst(object[] items) => items[0];

// Using generics: fully type-safe, no casting, no boxing for value types
public T GetFirst<T>(T[] items) => items[0];
int first = GetFirst(new int[] { 1, 2, 3 }); // no cast needed, no boxing
Real-world example Writing a single, reusable Stack<T> or Repository<T> class that works safely and efficiently with any specific type.

Common follow-ups: Why specifically does using 'object' for value types cause boxing, and why is that a performance concern?