C# StringBuilder GetChunks() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
StringBuilder

Definition

In C#, StringBuilder.GetChunks() returns an enumerator that walks the builder's text piece by piece. Internally, a large builder is not one array but a chain of smaller arrays (chunks). Each item in the foreach is a ReadOnlyMemory<char> holding one of those pieces, in order from the first character to the last.

This lets you send or inspect the text without building one big string, which helps with very large builders. How many chunks there are, and where they split, is an internal detail that can change with the text and the .NET version. So never depend on the chunk count; only use the characters. Use chunk.Span to read them and chunk.Length for their number. For the simple case, ToString() is easier.

An instance method of StringBuilder (using System.Text;), called as sb.GetChunks(...). The builder is a mutable buffer that changes in place, unlike an immutable string. It is not thread-safe. GetChunks exists in .NET Core 3.0 and later (including .NET 5 and newer). It is not in .NET Framework.

Syntax

Use it in a foreach loop. Each chunk is a ReadOnlyMemory<char>.

C#
StringBuilder sb = new StringBuilder("some text");
foreach (ReadOnlyMemory<char> chunk in sb.GetChunks()) {
    ReadOnlySpan<char> chars = chunk.Span;  // read the characters
    int n = chunk.Length;                   // how many in this chunk
}
CallWhat it does
foreach (var chunk in sb.GetChunks())Visits every internal piece, first to last.
chunk.SpanA ReadOnlySpan<char> over the chunk's characters.
chunk.LengthThe number of characters in this chunk. All lengths add up to sb.Length.
writer.Write(chunk.Span)Pass each piece to a TextWriter or stream without making a string.

Do not change the builder while you loop over its chunks. Appending, removing, or clearing during the foreach can make the chunks wrong. The chunks also point straight into the builder's memory, so do not keep them after the builder changes.

Library declarations
C#
public StringBuilder.ChunkEnumerator GetChunks();

// ChunkEnumerator (used by foreach):
//   public ReadOnlyMemory<char> Current { get; }
//   public bool MoveNext();
//   public ChunkEnumerator GetEnumerator();

Parameters

ParameterDescription
NoneGetChunks() takes no parameters.

Return Value

Return ValueDescription
StringBuilder.ChunkEnumeratorA struct you loop over with foreach. Each Current value is a ReadOnlyMemory<char> with one piece of the text.

C# Examples

Example 1 — Add Up the Chunk Lengths

Build a short phrase, loop over its chunks, and check that their lengths add up to Length.

C#
using System;
using System.Text;

class Program {
    static void Main() {
        StringBuilder sb = new StringBuilder();
        sb.Append("Stream ").Append("me ").Append("in pieces");

        int total = 0;
        foreach (ReadOnlyMemory<char> chunk in sb.GetChunks()) {
            total += chunk.Length;
        }

        Console.WriteLine(total);
        Console.WriteLine(total == sb.Length);
    }
}

How It Works

  1. Some text first. Three appends give Stream me in pieces, which is 7 + 3 + 9 = 19 characters.
  2. Loop over pieces. GetChunks() works directly in foreach; each round gives one ReadOnlyMemory<char>.
  3. Sum, do not count. Adding chunk.Length each time gives 19 whether the text sits in one chunk or several, which is why the chunk count is never printed.
  4. Matches Length. The total equals sb.Length, proving the chunks cover every character exactly once.

Example 2 — Count a Character Without ToString

Build a 200-character text in a loop and count its commas by reading each chunk's span, so no big string is ever created.

C#
using System;
using System.Text;

class Program {
    static void Main() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 50; i++) {
            sb.Append("a,b;");
        }

        int commas = 0;
        foreach (ReadOnlyMemory<char> chunk in sb.GetChunks()) {
            foreach (char ch in chunk.Span) {
                if (ch == ',') {
                    commas++;
                }
            }
        }

        Console.WriteLine(sb.Length);
        Console.WriteLine(commas);
    }
}

How It Works

  1. A longer builder. 50 rounds of the 4-character text a,b; give 200 characters, enough that the builder may grow into more than one chunk.
  2. Two loops. The outer foreach walks the chunks; the inner one walks the characters of chunk.Span.
  3. No copy. The span reads the builder's memory directly, so the 200 characters are never copied into a new string.
  4. The answer. Each a,b; holds one comma, so the count is 50, however the text happens to be split.

Example 3 — Copy Every Chunk Into One Array

Copy each chunk into the right place of a char[], using a running position, and print the rebuilt text.

C#
using System;
using System.Text;

class Program {
    static void Main() {
        StringBuilder sb = new StringBuilder("Hello");
        sb.Append(", ").Append("chunks").Append('!');

        char[] all = new char[sb.Length];
        int pos = 0;
        foreach (ReadOnlyMemory<char> chunk in sb.GetChunks()) {
            chunk.Span.CopyTo(all.AsSpan(pos));
            pos += chunk.Length;
        }

        Console.WriteLine(new string(all));
        Console.WriteLine(pos);
    }
}

How It Works

  1. Right-sized target. new char[sb.Length] has exactly one slot per character, 14 in total.
  2. Running position. pos starts at 0 and grows by each chunk's length, so the next chunk lands right after the previous one.
  3. Span to span. chunk.Span.CopyTo(all.AsSpan(pos)) copies the chunk into the array starting at pos.
  4. Same text back. The array spells Hello, chunks! and pos ends at 14. This is the pattern for writing chunks to a file or network buffer.

Frequently Asked Questions

It returns an enumerator over the builder's internal pieces of text. Each piece is a ReadOnlyMemory<char>, and together they hold every character in order.
.NET Core 3.0 and later, including .NET 5 and newer. It is not available in .NET Framework.
It depends on how the builder grew and on the .NET version, so do not rely on it. Use the characters and lengths, not the number of chunks.
No. Appending, removing, or clearing while you loop over the chunks can give wrong results. Finish the loop first, then change the builder.
When the text is large and you want to write or scan it without making one big string. For normal sizes, ToString is simpler.

Next: Insert()

Put text or a value at any position; the characters after it move to the right.

Insert() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful