Lesson 9: Generics and variance
Without generics every data structure gets duplicated: AppleBasket, OrangeBasket — or worse, a basket of object with dangerous runtime casts. In this lesson we write one class with a type parameter <T>, and learn when out and in allow an apple basket to stand where a fruit basket is expected.
Generics are like one baking mold filled with a different batter each time — the mold never changes, only the content. And the safety rule is simple: taking "a fruit" out of an apple crate is safe, but tossing a watermelon into it is not.
- Generics and variance
- Type parameters let one class or interface serve every type safely; variance (out/in) decides when a subtype may replace a base type.
- type parameter <T>
- A placeholder type the calling code fills in — Basket<Apple>, Basket<string> — enforced by the compiler at compile time, no casts.
- covariance (out)
- When T appears only as output, IProducer<Apple> is allowed as IProducer<Fruit> — everything that comes out is a fruit. The reverse direction, in, covers input-only T.