Roadmap › OOP Concepts in C# › Module: Relationships and Design
Lessons in this course (15)
13. Composition over inheritance
Intermediate★ Must knowLesson 13 of 15
Deep inheritance trees are fragile: a change in the base class ripples down ("fragile base class problem"), and you inherit things you don't need. Prefer composing objects from small pieces and inheriting only for true "is-a" relationships.
csharp
// Inheritance explosion: EmailNotifier, SmsNotifier, EmailAndSmsNotifier, LoggedEmailNotifier...
// Composition: combine behaviours at runtime
public interface IChannel { Task SendAsync(string to, string msg); }
public class Notifier(IEnumerable<IChannel> channels)
{
public Task NotifyAsync(string to, string msg) => Task.WhenAll(channels.Select(c => c.SendAsync(to, msg)));
}