C# Stack TrimExcess() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Stack

Definition

In C#, Stack.TrimExcess() shrinks the stack's internal storage so it fits the number of items it holds right now. It is the opposite of EnsureCapacity().

A stack that once held a million items keeps its big array even after you pop most of them, because Pop() and Clear() do not hand memory back. Think of a tall shelf that stays in the hall after the delivery is gone. TrimExcess swaps it for a short one. The items, their order, and Count do not change.

This is an instance member of Stack<T> (System.Collections.Generic). Call it on a stack variable, such as history.TrimExcess(...). 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>.

Syntax

Call TrimExcess with no arguments after the stack has become much smaller.

C#
Stack<int> stack = new Stack<int>();
for (int i = 0; i < 1000; i++) stack.Push(i);

while (stack.Count > 3) stack.Pop();   // only 0, 1, 2 are left
stack.TrimExcess();                    // shrink the storage to fit 3 items
CallWhat it does
stack.TrimExcess()Shrinks the storage to fit the current Count. Items stay in order.
stack.Clear(); stack.TrimExcess();Empty the stack and give its memory back.
stack.EnsureCapacity(1000)The reverse: reserve extra room. See EnsureCapacity().

TrimExcess may copy the items into a new, smaller array, so it costs time proportional to the number of items. It only shrinks when there is a good amount of unused space (the stack must be clearly below its capacity), otherwise it may do nothing. Call it once after a big clean-up, not inside a loop. A Stack<T> has no public Capacity property, so you cannot see the change, only the memory profile does.

Library declarations
C#
public void TrimExcess();

Parameters

ParameterDescription
NoneTrimExcess() takes no parameters.

Return Value

Return ValueDescription
voidNothing is returned. The items, their order, and Count are the same as before the call.

C# Examples

Example 1 — Trim a Stack After Most Items Are Popped

Push 1000 numbers, pop all but three, and call TrimExcess. The remaining items are unchanged.

C#
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        Stack<int> stack = new Stack<int>();
        for (int i = 0; i < 1000; i++) {
            stack.Push(i);
        }

        while (stack.Count > 3) {
            stack.Pop();
        }
        stack.TrimExcess();

        Console.WriteLine(stack.Count);
        Console.WriteLine(stack.Peek());
        Console.WriteLine(string.Join(", ", stack));
    }
}

How It Works

  1. A tall stack first. The loop pushes 0 to 999, so the stack reserved a lot of storage for 1000 items.
  2. Pop nearly all. The while loop pops from the top until only 3 items remain: 0, 1, and 2. The storage is still large afterward.
  3. Release the spare room. TrimExcess() fits the storage to 3 items. It prints nothing and leaves every item as it was.
  4. Same answers. Count is 3, the top is 2, and the order from the top is still 2, 1, 0.

Example 2 — Trim an Empty Stack and Use It Again

Clear a stack, trim it, and keep working with it. See that trimming an empty stack is safe.

C#
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        Stack<string> words = new Stack<string>();
        words.Push("alpha");
        words.Push("beta");
        words.Push("gamma");

        words.Clear();
        words.TrimExcess();
        Console.WriteLine(words.Count);

        words.TrimExcess();
        words.Push("delta");
        Console.WriteLine(words.Count);
        Console.WriteLine(words.Peek());
    }
}

How It Works

  1. Start by emptying. Clear() drops the items but keeps the big array. TrimExcess() then lets that spare room go.
  2. Safe when empty. Trimming a stack with no items raises no error, and the first printed Count is 0.
  3. A repeat trim. The second TrimExcess() finds nothing to shrink, so it is harmless.
  4. Still usable. The stack simply gets storage again when it needs it. Push("delta") works, Count is 1, and delta is on top.

Example 3 — A Helper That Pops Down and Trims

A small method pops a tall stack down to a chosen size and trims once. Call it twice with smaller and smaller targets.

C#
using System;
using System.Collections.Generic;

class Program {
    static void ShrinkTo(Stack<int> stack, int keep) {
        while (stack.Count > keep) {
            stack.Pop();
        }
        stack.TrimExcess();
    }

    static void Main() {
        Stack<int> stack = new Stack<int>();
        for (int i = 0; i < 200; i++) {
            stack.Push(i);
        }

        ShrinkTo(stack, 50);
        Console.WriteLine(stack.Count + " " + stack.Peek());

        ShrinkTo(stack, 2);
        Console.WriteLine(stack.Count + " " + stack.Peek());
    }
}

How It Works

  1. A reusable helper. ShrinkTo pops until only keep items are left, then calls TrimExcess() one time at the end of the clean-up.
  2. First target: 50. The numbers 0 to 199 are stacked, so popping 150 times leaves 0 to 49. The top is 49, and the first line is 50 49.
  3. Second target: 2. The same helper pops 48 more items. Only 0 and 1 remain, with 1 on top, so the second line is 2 1.
  4. Trim after the loop. The trim sits outside the while loop on purpose. Trimming on every pop would copy the items again and again.

Frequently Asked Questions

It shrinks the internal storage of the stack so it fits the number of items it holds now. The items, their order, and Count stay exactly the same.
No. It never removes or changes an item. It only releases unused storage space.
Once, after a big clean-up that left a once-tall stack short for a long time. Do not call it inside a loop, because copying the items takes time.
Clear removes the items but keeps the storage. Call TrimExcess after Clear if you also want to give the space back.
Not with a Stack<T>. It has no public Capacity property, so the effect shows up in memory use rather than in your program output.

Next: TryPeek()

Try to read the top item without removing it; returns false instead of throwing on an empty stack.

TryPeek() 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.

7 people found this page helpful