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
}
Call
What it does
foreach (var chunk in sb.GetChunks())
Visits every internal piece, first to last.
chunk.Span
A ReadOnlySpan<char> over the chunk's characters.
chunk.Length
The 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
Parameter
Description
None
GetChunks() takes no parameters.
Return Value
Return Value
Description
StringBuilder.ChunkEnumerator
A 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);
}
}
Output
19
True
How It Works
Some text first. Three appends give Stream me in pieces, which is 7 + 3 + 9 = 19 characters.
Loop over pieces.GetChunks() works directly in foreach; each round gives one ReadOnlyMemory<char>.
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.
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);
}
}
Output
200
50
How It Works
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.
Two loops. The outer foreach walks the chunks; the inner one walks the characters of chunk.Span.
No copy. The span reads the builder's memory directly, so the 200 characters are never copied into a new string.
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);
}
}
Output
Hello, chunks!
14
How It Works
Right-sized target.new char[sb.Length] has exactly one slot per character, 14 in total.
Running position.pos starts at 0 and grows by each chunk's length, so the next chunk lands right after the previous one.
Span to span.chunk.Span.CopyTo(all.AsSpan(pos)) copies the chunk into the array starting at pos.
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.