C# HashSet TrimExcess() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashSet

Definition

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

A set that once held a million items keeps its big storage even after you remove most of them, because Remove() and Clear() do not hand memory back. Think of a suitcase that is still large after you took the clothes out. TrimExcess packs everything into a smaller case. The items and Count do not change.

This is an instance member of HashSet<T> (System.Collections.Generic). Call it on a set variable, such as numbers.TrimExcess(...). A HashSet<T> is a class, so two variables can share one set. It keeps unique items only and does not promise any order. TrimExcess has been part of HashSet<T> for a long time and is also available in newer .NET versions.

Syntax

Call TrimExcess with no arguments after a big clean-up.

C#
HashSet<int> numbers = new HashSet<int>();
for (int i = 0; i < 1000; i++) numbers.Add(i);

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

TrimExcess may need to rebuild the set's internal tables, so it costs time proportional to the number of items. Call it once after a big clean-up, not inside a loop. Because HashSet has no public Capacity property, you cannot see the size 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 and Count are the same as before the call.

C# Examples

Example 1 — Trim a Set After a Big Clean-Up

Fill a set with 1000 numbers, remove all but three with RemoveWhere, and call TrimExcess.

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

class Program {
    static void Main() {
        HashSet<int> numbers = new HashSet<int>();
        for (int i = 0; i < 1000; i++) {
            numbers.Add(i);
        }

        int removed = numbers.RemoveWhere(n => n >= 3);
        numbers.TrimExcess();

        Console.WriteLine(removed);
        Console.WriteLine(numbers.Count);
        Console.WriteLine(numbers.Contains(2));
        Console.WriteLine(numbers.Contains(500));
    }
}

How It Works

  1. Big set first. The loop adds 0 to 999, so the set reserved a lot of storage for 1000 items.
  2. Big clean-up. RemoveWhere(n => n >= 3) deletes 997 items, but the storage is still large afterward.
  3. Give space back. TrimExcess() rebuilds the storage to fit only 3 items. It does not print anything and does not change which items exist.
  4. Same answers. Count is 3, Contains(2) is True, and Contains(500) is False, exactly as before the trim.

Example 2 — Trim an Empty Set and Use It Again

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

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

class Program {
    static void Main() {
        HashSet<string> words = new HashSet<string> { "alpha", "beta", "gamma" };

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

        words.TrimExcess();
        Console.WriteLine(words.Add("delta"));
        Console.WriteLine(words.Count);
        Console.WriteLine(words.Contains("delta"));
    }
}

How It Works

  1. Empty first. Clear() removes the items but keeps the storage. TrimExcess() then lets the storage go.
  2. Safe on empty. Trimming a set with no items raises no error. The first printed Count is 0.
  3. Trim again. A second TrimExcess() has nothing left to shrink, so it does nothing harmful.
  4. Still usable. The set simply gets new storage when it needs it, so Add("delta") returns True and Count is 1.

Example 3 — Build a Lookup Set, Then Trim It Once

A method builds a large set, keeps only every 100th number, trims the set once, and returns a small read-only lookup.

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

class Program {
    static HashSet<int> BuildLookup() {
        HashSet<int> set = new HashSet<int>();
        for (int i = 0; i < 1000; i++) {
            set.Add(i);
        }

        set.RemoveWhere(n => n % 100 != 0);
        set.TrimExcess();
        return set;
    }

    static void Main() {
        HashSet<int> lookup = BuildLookup();

        Console.WriteLine(lookup.Count);
        Console.WriteLine(lookup.Contains(300));
        Console.WriteLine(lookup.Contains(301));
    }
}

How It Works

  1. Temporary work. Inside BuildLookup the set first holds 1000 numbers, then RemoveWhere deletes every number that is not a multiple of 100.
  2. Ten survive. The multiples 0, 100, 200, up to 900 stay, so the set ends with 10 items.
  3. Trim once, at the end. The method calls TrimExcess() one time, right before returning, because that is when the set is small and will stay small.
  4. Lookup works. The caller gets a compact set. Contains(300) is True and Contains(301) is False.

Frequently Asked Questions

It shrinks the internal storage of the set so it fits the number of items it holds now. The items 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-large set small for a long time. Do not call it inside a loop, because rebuilding the storage 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 HashSet. It has no public Capacity property, so the effect shows up in memory use rather than in your program output.

Next: TryGetValue()

Look up an item and get back the exact copy stored in the HashSet, if there is one.

TryGetValue() 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