Generics in C#
Type-safe reusable code. Write once, use for any type without boxing.
60-Second Version: Generics = templates with type placeholders. Kunal builds one pizza box that fits any size pizza. No duplicate boxes for small, medium, large.
1. Why Generics? Stop Casting Everything
Before generics: ArrayList stored object. Put int in, get object out, cast back. Slow, unsafe. Prerna puts a string by mistake, runtime crash.
// Old way: boxing + runtime crashes
ArrayList list = new ArrayList();
list.Add(5); // int โ object = boxing
int x = (int)list[0]; // unbox + cast
// Generics: compile-time safety, no boxing
List<int> list = new List<int>();
list.Add(5); // No boxing
int x = list[0]; // No cast
2. Generic Classes & Methods: <T> Is a Placeholder
T means "Type". Compiler replaces it. Kaushal writes one PizzaBox<T>. Use it for PizzaBox<Margherita> or PizzaBox<Pepperoni>.
public class PizzaBox<T> {
public T Pizza { get; set; }
}
var vegBox = new PizzaBox<VegPizza>();
vegBox.Pizza = new VegPizza(); // Only VegPizza allowed
3. Constraints: Tell T What It Can Be
Want T to have a method? Add constraint. where T : IPizza means T must implement IPizza.
public class Oven<T> where T : IPizza, new() {
public T Bake() {
T pizza = new T(); // new() constraint allows this
pizza.Cook(); // IPizza constraint allows this
return pizza;
}
}
Beginner Trap: Sanju writes
if(item == null) in generic method. Breaks for int. Fix: if(EqualityComparer<T>.Default.Equals(item, default(T))) or constrain where T : class.
No comments yet. Be the first to share your thoughts!