In C#, StringBuilder.EnsureCapacity(capacity) makes sure the builder can hold at leastcapacity characters without asking for more memory. If it already has that much room, nothing happens. The method returns the capacity the builder has after the call.
Two numbers matter here. Length is how many characters the builder holds now; Capacity is how many fit in the memory it has reserved (16 for a new, empty builder). When appends go past the capacity, the builder grows by itself. If you know roughly how big the text will be, reserving the room up front avoids several small growth steps. It never changes the text, and it never shrinks the builder; Clear() keeps the room too.
An instance method of StringBuilder (using System.Text;), called as sb.EnsureCapacity(...). The builder is a mutable buffer that changes in place, unlike an immutable string. It is not thread-safe. StringBuilder.EnsureCapacity exists in every .NET version, including .NET Framework.
Syntax
Pass the number of characters you expect. The return value is the capacity now in place.
C#
StringBuilder sb = new StringBuilder(); // Capacity 16
int cap = sb.EnsureCapacity(500); // cap is at least 500
// sb.Length is still 0
StringBuilder roomy = new StringBuilder(500); // same idea, at creation
Call
What it does
sb.EnsureCapacity(500)
Grows the room to at least 500 characters if it is smaller.
sb.EnsureCapacity(10)
If the builder already has more room, nothing changes; the current capacity is returned.
new StringBuilder(500)
Picks the starting capacity when you create the builder.
sb.Capacity = 500
Sets the capacity directly. It must not be less than Length.
A negative value throws ArgumentOutOfRangeException, and so does a value above MaxCapacity. The returned number is at least what you asked for; the exact figure is an implementation detail, so compare with >= rather than printing it. This is only a speed tip: your program gives the same text with or without it.
Library declarations
C#
public int EnsureCapacity(int capacity);
// related members
public int Capacity { get; set; }
public int Length { get; set; }
public int MaxCapacity { get; }
Parameters
Parameter
Description
capacity
Required. The minimum number of characters the builder should have room for. Must be 0 or more.
Return Value
Return Value
Description
int
The builder's capacity after the call: the old capacity if it was already big enough, otherwise at least capacity.
C# Examples
Example 1 — Reserve Room Before Building
Check the default capacity of a new builder, reserve room for 200 characters, and confirm no text was added.
C#
using System;
using System.Text;
class Program {
static void Main() {
StringBuilder sb = new StringBuilder();
Console.WriteLine(sb.Capacity);
int cap = sb.EnsureCapacity(200);
Console.WriteLine(cap >= 200);
Console.WriteLine(sb.Capacity == cap);
Console.WriteLine(sb.Length);
}
}
Output
16
True
True
0
How It Works
The default room. A builder made with new StringBuilder() starts with a capacity of 16 characters.
Ask for more.EnsureCapacity(200) grows the room, and the returned value is at least 200, so the check prints True.
Return value equals Capacity. The number handed back is the same as reading the Capacity property afterwards.
Still empty.Length stays 0: reserving room does not put any characters in the builder.
Example 2 — A Smaller Request Changes Nothing
Ask a roomy builder for less than it already has, check that the text survives, and try a negative number.
C#
using System;
using System.Text;
class Program {
static void Main() {
StringBuilder sb = new StringBuilder(64);
sb.Append("ready");
int before = sb.Capacity;
int after = sb.EnsureCapacity(10);
Console.WriteLine(before + " -> " + after);
Console.WriteLine(sb.ToString());
try {
sb.EnsureCapacity(-5);
} catch (ArgumentOutOfRangeException) {
Console.WriteLine("capacity cannot be negative");
}
}
}
Output
64 -> 64
ready
capacity cannot be negative
How It Works
Plenty of room already.new StringBuilder(64) reserves 64 characters, and ready uses only 5 of them.
No shrinking. Asking for 10 is less than 64, so EnsureCapacity leaves the room alone and returns 64, giving 64 -> 64.
Text untouched. The builder still holds ready; capacity calls never add, remove, or move characters.
Bad input. A negative capacity makes no sense, so EnsureCapacity(-5) throws ArgumentOutOfRangeException and the catch block reports it.
Example 3 — Reserve Once, Then Append 2000 Characters
Reserve 3000 characters, append 1000 two-letter pieces, and check that the builder never needed to grow.
C#
using System;
using System.Text;
class Program {
static void Main() {
StringBuilder sb = new StringBuilder();
int reserved = sb.EnsureCapacity(3000);
for (int i = 0; i < 1000; i++) {
sb.Append("ab");
}
Console.WriteLine(sb.Length);
Console.WriteLine(sb.Capacity == reserved);
Console.WriteLine(sb.ToString(0, 6));
}
}
Output
2000
True
ababab
How It Works
Reserve up front. The builder gets room for at least 3000 characters before the loop, and reserved remembers that capacity.
Fill it. 1000 appends of ab add 2000 characters, so Length is 2000.
No growth needed. 2000 is below the reserved room, so Capacity is still exactly reserved and the check prints True.
Peek at the start.ToString(0, 6) copies only the first six characters, ababab, instead of the whole 2000.
Frequently Asked Questions
It makes sure the builder has room for at least the given number of characters, growing its memory if needed, and returns the capacity after the call. The text does not change.
Length is the number of characters stored now. Capacity is how many characters fit before the builder must reserve more memory. Capacity is always at least Length.
No. If the builder already has enough room, nothing changes. To shrink it, set the Capacity property to a smaller value that is still at least Length.
A new StringBuilder() starts with a capacity of 16 characters. It grows automatically as you append.
No, it is optional. It only saves a few growth steps when you build large texts and know the size in advance; new StringBuilder(size) does the same at creation.