Course contentsShow
← C#
Lesson 115 of 1,9081. C# Language FoundationsFree lesson

Composite Pattern Trees

Represent part-whole hierarchies as single objects for uniform processing.

In this lesson, you will learn how to use the Composite Pattern to treat individual objects and groups of objects as if they were the same thing.

The Core Idea: Uniformity

Imagine you are building a file system. You have File objects (the leaves) and Folder objects (the containers). A Folder can contain files, but it can also contain other folders. If you want to calculate the total size of a directory, you shouldn’t have to write different code for a single file versus a folder full of files. The Composite Pattern lets you "compose" these objects into a tree structure so that you can call a single method, like GetSize(), on the top-level object, and it recursively processes the entire branch.

Seeing it in Code

To achieve this, both your "leaf" (File) and your "composite" (Folder) must implement the same interface.

public interface IFileSystemItem {
    int GetSize();
}

public class File : IFileSystemItem {
    public int Size { get; init; }
    public int GetSize() => Size;
}

public class Folder : IFileSystemItem {
    private readonly List<IFileSystemItem> _children = new();

    public void Add(IFileSystemItem item) => _children.Add(item);

    public int GetSize() {
        // Here is the magic: we treat all children the same!
        return _children.Sum(child => child.GetSize());
    }
}

Why This Matters

By forcing the Folder to implement IFileSystemItem, we allow the client code to interact with the system without knowing if it is looking at a single file or a deeply nested tree. When you call GetSize() on a root folder, the request propagates down the tree automatically.

The Folder doesn't care if its children are File objects or other Folder objects; it simply asks them for their size. This "uniform processing" simplifies your logic significantly, as you no longer need complex if/else checks to determine if an object is a container or a leaf.

Key Takeaway: The Composite Pattern uses a common interface to treat individual objects and object containers identically, allowing you to build and traverse complex tree structures with ease.