C# Dictionary EnsureCapacity() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Dictionary

Definition

In C#, Dictionary.EnsureCapacity(capacity) prepares the dictionary to hold at least that many pairs. It reserves the space now, so the dictionary does not have to grow again and again while you add items.

Think of it like booking a big table at a restaurant before the guests arrive. It does not add any pairs; Count stays the same. It only makes later Add() calls cheaper when you already know roughly how many items are coming.

This is an instance member of Dictionary<TKey,TValue> (System.Collections.Generic). Call it on a dictionary variable, such as ages.EnsureCapacity(...). A dictionary is a class, so two variables can share one dictionary. EnsureCapacity exists in .NET 5 and later. It is not in .NET Framework.

Syntax

Pass the number of entries you expect. The method returns the capacity the dictionary now has.

C#
Dictionary<string, int> ages = new Dictionary<string, int>();
int cap = ages.EnsureCapacity(100);   // cap is at least 100
// ages.Count is still 0
CallWhat it does
ages.EnsureCapacity(100)Makes room for at least 100 pairs and returns the real capacity (100 or more).
new Dictionary<string,int>(100)Sets the starting capacity when you create the dictionary.
ages.TrimExcess()The opposite job: shrink unused space. See TrimExcess().

The returned capacity is often a bit bigger than the number you passed, because the dictionary rounds up to a size that works well with hashing. If the current capacity is already large enough, nothing changes. A negative number throws ArgumentOutOfRangeException.

Library declarations
C#
public int EnsureCapacity(int capacity);

Parameters

ParameterDescription
capacityRequired. The number of pairs the dictionary must be able to hold. It must be 0 or more.

Return Value

Return ValueDescription
intThe capacity of the dictionary after the call. It is at least the number you asked for. The exact number is an internal detail, so do not print it in your own logic.

C# Examples

Example 1 — Reserve Room for 100 Pairs

Call EnsureCapacity on an empty dictionary and check that nothing was added.

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

class Program {
    static void Main() {
        Dictionary<string, int> ages = new Dictionary<string, int>();
        int cap = ages.EnsureCapacity(100);

        Console.WriteLine(cap >= 100);
        Console.WriteLine(ages.Count);

        ages.Add("Asha", 25);
        Console.WriteLine(ages.Count);
    }
}

How It Works

  1. Return value. cap is the new capacity. The code prints only the comparison cap >= 100, because the exact number is an internal detail.
  2. No pairs yet. Reserving space does not add anything, so Count is 0.
  3. Add works as usual. After one Add, Count is 1.
  4. Same behavior. Only speed and memory plans are different; the dictionary acts like any other.

Example 2 — Fill 1000 Pairs After Pre-Sizing

When you know you will add 1000 pairs, reserve room first and then add them in a loop.

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

class Program {
    static void Main() {
        Dictionary<int, int> squares = new Dictionary<int, int>();
        squares.EnsureCapacity(1000);

        for (int i = 0; i < 1000; i++) {
            squares.Add(i, i * i);
        }

        Console.WriteLine(squares.Count);
        Console.WriteLine(squares[30]);
        Console.WriteLine(squares.ContainsKey(999));
    }
}

How It Works

  1. Reserve first. EnsureCapacity(1000) is called before the loop, so the dictionary does not need to grow while it fills.
  2. Loop of Add calls. Keys 0 to 999 are all new, so every Add succeeds and Count is 1000.
  3. Values are squares. The key 30 maps to 30 times 30, which is 900.
  4. Result is the same. The data looks exactly as it would without pre-sizing; the gain is fewer resizes and less memory churn.

Example 3 — Smaller Request and Negative Request

Ask for a smaller capacity after a bigger one, then try a negative number.

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

class Program {
    static void Main() {
        Dictionary<string, int> ages = new Dictionary<string, int>();
        int big = ages.EnsureCapacity(50);
        int small = ages.EnsureCapacity(10);
        Console.WriteLine(small >= big);

        try {
            ages.EnsureCapacity(-1);
        } catch (ArgumentOutOfRangeException) {
            Console.WriteLine("Negative capacity");
        }
    }
}

How It Works

  1. Big request. The first call reserves room for at least 50 pairs and returns that capacity.
  2. Small request. Asking for only 10 afterwards does not shrink anything, because the space is already large enough.
  3. Comparison. small >= big prints True, which shows that the capacity did not go down.
  4. Negative number. A capacity below 0 makes no sense, so ArgumentOutOfRangeException is thrown and caught.

Frequently Asked Questions

It makes sure the dictionary has room for at least the number of pairs you pass, so it does not need to grow while you add them. It returns the new capacity.
No. Count stays the same. It only reserves space.
It is available in .NET 5 and later. It is not in .NET Framework. In older code, set the capacity in the constructor, such as new Dictionary<string,int>(100).
The dictionary rounds the size up to a value that suits its hash table, so the result can be larger than what you asked for.
Use it when you know about how many items you will add, especially for thousands of items. For small dictionaries it makes no real difference.

Next: GetEnumerator()

Get an enumerator that visits every KeyValuePair; foreach calls it for you.

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

11 people found this page helpful