Composite Pattern Implementation in C#
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 Pattern in C#: what you actually reach for
C# implementation
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 FreeThe C#-specific trap
Performance in C#, beyond the O(n)
Real-World Applications
Interview Tips & Practice
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).
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 trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.