In C#, HashSet.EnsureCapacity(capacity) prepares the set to hold at least that many items. It reserves the space now, so the set does not have to grow again and again while you add items.
Think of booking a big table before the guests arrive. It does not add any items; Count stays the same. It only makes later Add() calls cheaper when you already know about how many items are coming. The result is a speed and memory tip, never a change in what the set contains.
This is an instance member of HashSet<T> (System.Collections.Generic). Call it on a set variable, such as numbers.EnsureCapacity(...). A HashSet<T> is a class, so two variables can share one set. It keeps unique items only and does not promise any order. EnsureCapacity exists in newer .NET versions (.NET Core and .NET 5 and later). 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 set now has.
C#
HashSet<int> numbers = new HashSet<int>();
int cap = numbers.EnsureCapacity(100); // cap is at least 100
// numbers.Count is still 0
Call
What it does
numbers.EnsureCapacity(100)
Makes room for at least 100 items and returns the real capacity (100 or more).
numbers.EnsureCapacity(0)
Allowed. Nothing special happens; it returns the current capacity.
numbers.TrimExcess()
The opposite job: give back unused space. See TrimExcess().
The returned capacity is often a bit bigger than the number you passed, because the set rounds up to a size that works well with hashing. If the set already has enough room, nothing changes. A negative number throws ArgumentOutOfRangeException. HashSet has no public Capacity property, so the return value is the way to see it.
Library declarations
C#
public int EnsureCapacity(int capacity);
Parameters
Parameter
Description
capacity
Required. The number of items the set must be able to hold. It must be 0 or more.
Return Value
Return Value
Description
int
The capacity of the set after the call. It is at least the number you asked for. The exact number is an internal detail, so do not print it or rely on it in your own logic.
C# Examples
Example 1 — Reserve Room for 100 Items
Call EnsureCapacity on an empty set and check that nothing was added.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
HashSet<int> numbers = new HashSet<int>();
int cap = numbers.EnsureCapacity(100);
Console.WriteLine(cap >= 100);
Console.WriteLine(numbers.Count);
numbers.Add(7);
Console.WriteLine(numbers.Count);
}
}
Output
True
0
1
How It Works
Return value.cap is the new capacity. The code prints only the comparison cap >= 100, since the exact number is an internal detail.
Still empty. Reserving room adds no items, so Count is 0.
Add works as usual. After one Add, Count is 1.
Same behavior either way. A set with reserved room acts just like any other set. Only the speed plan is different.
Example 2 — Load Many Items After Reserving Room
Reserve space for 1000 items, then add numbers from a loop where some values repeat.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
HashSet<int> numbers = new HashSet<int>();
numbers.EnsureCapacity(1000);
int added = 0;
for (int i = 0; i < 1000; i++) {
if (numbers.Add(i % 800)) {
added++;
}
}
Console.WriteLine(added);
Console.WriteLine(numbers.Count);
Console.WriteLine(numbers.Contains(799));
}
}
Output
800
800
True
How It Works
Reserve first. The call tells the set that up to 1000 items may come, so it can allocate once instead of growing in steps.
Values repeat.i % 800 turns 800 to 999 back into 0 to 199, which are already in the set. Those 200 calls to Add return false.
Count real adds. The variable added goes up only when Add returns true, so it ends at 800.
Reserved is not full. The set holds 800 distinct numbers, fewer than the 1000 reserved. Contains(799) is True.
Example 3 — Contents Stay, Small Requests, and Bad Values
Check that existing items survive, that asking for less than you have is harmless, and that a negative number throws.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
HashSet<int> numbers = new HashSet<int> { 1, 2, 3 };
int big = numbers.EnsureCapacity(50);
Console.WriteLine(big >= 50);
Console.WriteLine(numbers.Count);
Console.WriteLine(numbers.Contains(2));
int small = numbers.EnsureCapacity(10);
Console.WriteLine(small >= big);
try {
numbers.EnsureCapacity(-1);
} catch (ArgumentOutOfRangeException) {
Console.WriteLine("negative capacity");
}
}
}
Output
True
3
True
True
negative capacity
How It Works
Items survive. Growing the space moves the items internally, but Count stays 3 and Contains(2) is True.
Asking for less. The set already has room for at least 50, so EnsureCapacity(10) does not shrink it. It returns the current capacity, which is not smaller than big.
Never shrinks. That is why the comparison small >= big prints True. To give space back, use TrimExcess.
Negative is invalid. A capacity below 0 makes no sense, so the call throws ArgumentOutOfRangeException 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 set does not need to grow while you add items. It does not add or remove any item.
It returns the capacity the set has after the call. That is at least the number you passed, and often a little bigger.
It is in newer .NET versions, such as .NET Core and .NET 5 and later. It is not in classic .NET Framework. If your project does not compile with it, you are probably on an older version.
Newer .NET versions have a HashSet constructor that takes a starting capacity, such as new HashSet<int>(1000). EnsureCapacity is the way to do it after the set already exists.
Only when you add a large number of items. For small sets you will not notice any difference, so it is optional.