Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Composite Pattern Implementation in C#

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Composite Pattern runs in O(n) time and O(n) space, in C# as in every other language.
  • ✓An interface implemented by a leaf and a composite holding an IReadOnlyList of it. IEnumerable with yield return makes the traversal lazy, and Directory.EnumerateFileSystemEntries with SearchOption.AllDirectories is the framework composite walker, deliberately enumerable rather than array-returning so it streams.
  • ✓Expose the traversal as IEnumerable<Node> so LINQ composes over it, but implement it with an explicit Stack rather than nested yield return for the reason below.
  • ✓The C# trap: Recursive iterators built from nested yield return are QUADRATIC in depth. Each yield return in a nested iterator bubbles the value up through one MoveNext call per level, so producing n items from a tree of depth d costs O(n times d) MoveNext calls rather than O(n).
  • ✓Every yield return method compiles to a generated state-machine class allocated per enumeration, so the nested-recursion form allocates one per node per level as well as making the calls quadratic.

What Composite Pattern actually is

Composite lets a client treat a single object and a tree of objects through one interface, so a leaf and a branch both answer the same call and the branch answers by delegating to its children. The pattern itself is four lines of recursion; what makes it a genuinely different problem in each of these eight languages is everything AROUND the recursion. How deep can the stack actually go before it breaks, and does the runtime grow it or kill the process? Can the type system even express a type that contains itself? Who frees the tree, and does freeing it recurse as well? Two languages here cannot describe a recursive value without an explicit indirection, one grows its stack dynamically so depth is a non-issue, one makes the obvious iterator implementation quadratic, and two leak the whole tree if you add the parent pointer everyone eventually wants.

Composite Pattern in C#: what you actually reach for

An interface implemented by a leaf and a composite holding an IReadOnlyList of it. IEnumerable with yield return makes the traversal lazy, and Directory.EnumerateFileSystemEntries with SearchOption.AllDirectories is the framework composite walker, deliberately enumerable rather than array-returning so it streams. System.Text.Json and the Roslyn syntax API are both large composites in the framework worth reading as references.

C# implementation

Expose the traversal as IEnumerable<Node> so LINQ composes over it, but implement it with an explicit Stack rather than nested yield return for the reason below. Use a sealed record hierarchy with C# 9 records and switch on type patterns, and turn on the exhaustiveness warning so a new node type surfaces at compile time. Return IReadOnlyList<Node> for children, never List<Node>.
csharp
public abstract record Node
{
    public abstract int Total { get; }
}

public sealed record Leaf(int Size) : Node
{
    public override int Total => Size;
}

public sealed record Branch(IReadOnlyList<Node> Children) : Node
{
    public override int Total => Children.Sum(c => c.Total);

    // QUADRATIC: each item bubbles through one MoveNext per level of depth.
    public IEnumerable<Node> WalkSlow()
    {
        yield return this;
        foreach (var c in Children)
            if (c is Branch b) foreach (var n in b.WalkSlow()) yield return n;
            else yield return c;
    }

    // Flat, explicit stack: O(n) MoveNext calls and ONE state machine.
    public IEnumerable<Node> Walk()
    {
        var stack = new Stack<Node>();
        stack.Push(this);
        while (stack.Count > 0)
        {
            var n = stack.Pop();
            yield return n;
            if (n is Branch b)
                for (int i = b.Children.Count - 1; i >= 0; i--) stack.Push(b.Children[i]);
        }
    }
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The C#-specific trap

Recursive iterators built from nested yield return are QUADRATIC in depth. Each yield return in a nested iterator bubbles the value up through one MoveNext call per level, so producing n items from a tree of depth d costs O(n times d) MoveNext calls rather than O(n). On a balanced tree that is an extra log factor and easy to miss; on a degenerate deep tree it is catastrophic, and it is the single best-known performance trap in C# iterators. The fix is an explicit Stack in one flat iterator, which also removes the per-level state machine allocations.

Performance in C#, beyond the O(n)

Every yield return method compiles to a generated state-machine class allocated per enumeration, so the nested-recursion form allocates one per node per level as well as making the calls quadratic. The flat explicit-stack version allocates one stack and one state machine total. For a hot traversal, a struct enumerator exposed through a concrete return type avoids even the interface allocation, which is the technique List and Dictionary use to make foreach allocation-free. The asymptotic cost is the same in every language, O(n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Composite Pattern between languages.

Real-World Applications

Composite Pattern is used extensively in production software: framework internals, plugin architectures, state management libraries, and large-scale application architectures all rely on this pattern. In C#, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Composite Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Composite Pattern appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Composite Pattern over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Composite Pattern to build pattern recognition. In C#, demonstrate proficiency with LINQ and async patterns to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic C# code that is both correct and maintainable.

Frequently Asked Questions

Which C# type or library should I use for Composite Pattern?

An interface implemented by a leaf and a composite holding an IReadOnlyList of it. IEnumerable with yield return makes the traversal lazy, and Directory.EnumerateFileSystemEntries with SearchOption.AllDirectories is the framework composite walker, deliberately enumerable rather than array-returning so it streams. System.Text.Json and the Roslyn syntax API are both large composites in the framework worth reading as references.

What is the most common C# mistake when implementing Composite Pattern?

Recursive iterators built from nested yield return are QUADRATIC in depth. Each yield return in a nested iterator bubbles the value up through one MoveNext call per level, so producing n items from a tree of depth d costs O(n times d) MoveNext calls rather than O(n). On a balanced tree that is an extra log factor and easy to miss; on a degenerate deep tree it is catastrophic, and it is the single best-known performance trap in C# iterators. The fix is an explicit Stack in one flat iterator, which also removes the per-level state machine allocations.

How does Composite Pattern actually perform in C#?

Every yield return method compiles to a generated state-machine class allocated per enumeration, so the nested-recursion form allocates one per node per level as well as making the calls quadratic. The flat explicit-stack version allocates one stack and one state machine total. For a hot traversal, a struct enumerator exposed through a concrete return type avoids even the interface allocation, which is the technique List and Dictionary use to make foreach allocation-free. Time complexity is O(n) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

If you are a student, see what Replit offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.