In C#, Stack.EnsureCapacity(capacity) prepares the stack to hold at least that many items. It reserves the space now, so the stack does not have to allocate a bigger array again and again while you push items.
Think of clearing a tall shelf before a big delivery of plates. Nothing is stacked yet; Count stays the same. It only makes later Push() calls cheaper when you already know about how many items are coming. It is a speed and memory tip, never a change in what the stack contains.
This is an instance member of Stack<T> (System.Collections.Generic). Call it on a stack variable, such as history.EnsureCapacity(...). A Stack<T> is a class, so two variables can share one stack. It is last in, first out (LIFO): the newest item sits on top and leaves first. It is not thread-safe; for several threads use ConcurrentStack<T>. EnsureCapacity exists in newer .NET versions (it was added in recent .NET releases, around .NET 6). It is not in classic .NET Framework, so check your project version.
Syntax
Pass the number of items you expect. The method returns the capacity the stack now has.
C#
Stack<int> stack = new Stack<int>();
int cap = stack.EnsureCapacity(100); // cap is at least 100
// stack.Count is still 0
Call
What it does
stack.EnsureCapacity(100)
Makes room for at least 100 items and returns the real capacity (100 or more).
stack.EnsureCapacity(0)
Allowed. Nothing special happens; it returns the current capacity.
new Stack<int>(100)
Another way: pick the starting capacity in the constructor, when you create the stack.
stack.TrimExcess()
The opposite job: give back unused space. See TrimExcess().
The returned capacity can be bigger than the number you passed, because the stack may grow in steps. If it already has enough room, nothing changes. A negative number throws ArgumentOutOfRangeException. Stack<T> has no public Capacity property, so the return value is the way to see it, and the exact number is an internal detail.
Library declarations
C#
public int EnsureCapacity(int capacity);
Parameters
Parameter
Description
capacity
Required. The number of items the stack must be able to hold. It must be 0 or more.
Return Value
Return Value
Description
int
The capacity of the stack after the call. It is at least the number you asked for. Do not print it or rely on its exact value in your own logic.
C# Examples
Example 1 — Reserve Room for 100 Items
Call EnsureCapacity on an empty stack and check that nothing was added.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Stack<int> stack = new Stack<int>();
int cap = stack.EnsureCapacity(100);
Console.WriteLine(cap >= 100);
Console.WriteLine(stack.Count);
stack.Push(7);
Console.WriteLine(stack.Count);
}
}
Output
True
0
1
How It Works
What comes back.cap holds the new capacity. Only cap >= 100 is printed, because the exact figure is an internal detail of the library.
No items yet. Booking space puts nothing on the stack, so Count is 0 straight after the call.
Push as usual. After one Push(7), Count is 1.
Same behavior. A stack with reserved room acts like any other stack. Only the memory plan is different.
Example 2 — Load a Thousand Items After Reserving Room
Reserve space for 1000 items, then push the numbers 0 to 999. Check the top and the count.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Stack<int> stack = new Stack<int>();
stack.EnsureCapacity(1000);
for (int i = 0; i < 1000; i++) {
stack.Push(i);
}
Console.WriteLine(stack.Count);
Console.WriteLine(stack.Peek());
Console.WriteLine(stack.Contains(0));
}
}
Output
1000
999
True
How It Works
Reserve first. The call tells the stack that up to 1000 items may come, so it can allocate once instead of growing in several steps.
One thousand pushes. The loop calls Push 1000 times, so Count ends at 1000.
The top is the last number. The newest item is 999, so Peek() prints 999, not 0.
The bottom is still there.Contains(0) is True, because 0 was the first number pushed and sits at the very bottom.
Example 3 — Order Stays, Smaller Requests, and Bad Values
Pop and push to change the stack, reserve space, and see that the order stays. Then try a smaller number and a negative one.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Stack<int> stack = new Stack<int>(new int[] { 1, 2, 3 });
stack.Pop();
stack.Push(4);
int big = stack.EnsureCapacity(50);
Console.WriteLine(big >= 50);
Console.WriteLine(string.Join(", ", stack));
int small = stack.EnsureCapacity(10);
Console.WriteLine(small >= big);
try {
stack.EnsureCapacity(-1);
} catch (ArgumentOutOfRangeException) {
Console.WriteLine("negative capacity");
}
}
}
Output
True
4, 2, 1
True
negative capacity
How It Works
A changed stack. The stack starts as 1, 2, 3 with 3 on top. Pop() removes the 3 and Push(4) puts a 4 in its place, so it holds 4, 2, 1 from the top down.
The order survives growth. Making the array bigger copies the items, but the printed order is still top to bottom: 4, 2, 1.
It never shrinks. Asking for 10 when there is already room for at least 50 reduces nothing, so small >= big is True. To give space back, use TrimExcess.
A negative size is rejected. A capacity below 0 cannot be honored, so an ArgumentOutOfRangeException is thrown and the catch block prints a message.
Frequently Asked Questions
It reserves room for at least the number of items you ask for, so the stack does not need to grow while you push items. It does not add or remove any item.
It returns the capacity the stack has after the call. That is at least the number you passed, and may be a little bigger.
It is in newer .NET versions and is not in classic .NET Framework. The exact first version can differ from what you expect, so check the documentation for the version your project uses.
Yes. The constructor new Stack<int>(1000) takes a starting capacity. EnsureCapacity does the same job after the stack already exists.
Only when you push a large number of items. For small stacks you will not notice any difference, so it is optional.