🧩 Generics = Type-Safe Code
Object types are unsafe. Generics create type-safe reusable code. Performance, safety, flexibility.
❌ Object (Unsafe)
public class Stack
{
private object[] items;
public void Push(object item) { }
public object Pop() { }
}
Stack s = new Stack();
s.Push(123); // Boxed
int i = (int)s.Pop(); // Cast
✅ Generic (Type-Safe)
public class Stack{ private T[] items; public void Push(T item) { } public T Pop() { } } Stack s = new Stack (); s.Push(123); // No boxing int i = s.Pop(); // No casting
📝 Generic Examples
// Generic method
public class Helper
{
public static T GetDefault() => default(T);
public static T[] Swap(T a, T b) => new T[] { b, a };
}
// Generic class
public class Repository where T : class, new()
{
private List _items = new List();
public void Add(T item) => _items.Add(item);
public T GetById(int id) => _items.FirstOrDefault(x => GetId(x) == id);
private int GetId(T item) => (int)typeof(T).GetProperty("Id")?.GetValue(item);
}
// Multiple type parameters
public class Pair
{
public TKey Key { get; set; }
public TValue Value { get; set; }
}
// Constraints
where T : struct // Value type
where T : class // Reference type
where T : new() // Parameterless constructor
where T : BaseClass // Inherits from base
where T : IInterface // Implements interface
// Generic interface
public interface IRepository
{
T GetById(int id);
void Add(T entity);
void Update(T entity);
void Delete(int id);
}
✅ Generic Benefits
- Type safety (no casting)
- Performance (no boxing)
- Reusability (one class, many types)
- Clean code (less duplication)
- Maintainable (type-specific logic)
“Generics provide type safety and reusability. Essential for professional C# development.”
