Dictionary Properties and Methods in c#
When working with data in key-value pairs in C#, the Dictionary<TKey, TValue> is one of the most powerful and commonly used generic collections.
It allows you to store, retrieve and manage data efficiently using unique keys and associated values similar to hash maps in other languages like Java or JavaScript objects.
In this article, we’ll explore all major properties and methods of Dictionary in C#, along with examples, use cases and performance notes that every beginner and advanced developer should know.
What is a Dictionary in C#?
A Dictionary<TKey, TValue> in C# is a collection that stores key/value pairs. Each key must be unique and each key is associated with exactly one value. The Dictionary class belongs to the System.Collections.Generic namespace. Explore C# Dictionary in depth
Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();
Dictionary Properties in C#
Dictionary properties provide quick insights into its internal state such as count, keys, values and comparison logic. Let’s explore them one by one.
- Count : Retrieves the number of key/value pairs contained in the Dictionary.
var fruits = new Dictionary<int, string> { {1, "Apple"}, {2, "Banana"}, {3, "Mango"} }; Console.WriteLine("Total fruits: " + fruits.Count);Total fruits: 3
Use Case: Useful when validating dictionary size before iteration or conditionally adding elements.
- Keys :- Retrieves a collection with the Dictionary's keys in it.
var cityCodes = new Dictionary<int, string> { {91, "India"}, {1, "USA"}, {44, "UK"} }; foreach (var key in cityCodes.Keys) Console.WriteLine("Country Code: " + key);Country Code: 91 Country Code: 1 Country Code: 44
Tip: Keys are unique and can be accessed directly without duplication.
- Values :- Retrieves a collection containing all the values stored in the dictionary.
foreach (var value in cityCodes.Values) Console.WriteLine("Country: " + value);Country: India Country: USA Country: UK
Note: Values can be duplicate, unlike keys.
- Item[TKey] :- Gets or sets the value associated with the specified key using index notation [].
Dictionary<int, string> languages = new Dictionary<int, string>(); languages[1] = "C#"; languages[2] = "Java"; Console.WriteLine("Language at key 1: " + languages[1]);Language at key 1: C#
Important Note : Accessing a non-existent key using dict[key] throws a KeyNotFoundException. Use TryGetValue() to avoid this error.
- Comparer :- Gets the IEqualityComparer<T> that is used to determine equality of keys for the dictionary.
var dict = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); dict["One"] = 1; Console.WriteLine(dict.ContainsKey("one")); // TrueStringComparer.OrdinalIgnoreCase makes key lookups case-insensitive.
Dictionary Methods in C#
Let’s now dive into the core methods you’ll use frequently with Dictionary<TKey, TValue>.
1. Add(TKey, TValue)
Adds a new key-value pair to the dictionary.
dict.Add(4, "Python");
Throws ArgumentException if key already exists.
2. ContainsKey(TKey)
Checks whether a specific key exists in a dictionary. Returns true if the key is present, otherwise false.
if (dict.ContainsKey(2))
Console.WriteLine("Key 2 exists!");Use ContainsKey before accessing a key to avoid exceptions when the key might not exist.
3. ContainsValue(TValue)
Checks whether a specific value exists in a dictionary. Returns true if the value is found, otherwise false.
if (dict.ContainsValue("C#"))
Console.WriteLine("C# is available!");Use ContainsValue when you need to verify the presence of a value before performing operations like updates or removals.
4. Clear()
The Clear() method removes all key-value pairs from a dictionary, effectively emptying the collection.
dict.Clear(); Console.WriteLine(dict.Count); // 0
Time Complexity : O(n) ,The method needs to remove all n elements from the collection.
Use Case: Use Clear() when you want to reset a collection without creating a new instance.
5. EnsureCapacity(Int32)
The EnsureCapacity method ensures that the internal data structures of a Dictionary<TKey, TValue> can hold at least the specified number of entries without resizing. This helps improve performance when adding a large number of items.
var dict = new Dictionary<int, string>(); // Pre-allocate space for 1000 entries dict.EnsureCapacity(1000);
Time Complexity : O(n) only if the dictionary needs to resize internally. Otherwise, checking or setting capacity is O(1).
Use Case : Ideal when you know in advance that many entries will be added. It will prevents frequent rehashing/resizing, which improves insertion performance.
6. Equals(Object)
The Equals method checks whether the current dictionary is equal to another object. For Dictionary<TKey, TValue>, this performs a reference comparison, not a value comparison. Returns true if both references point to the same dictionary instance, otherwise returns false.
var dict1 = new Dictionary<int, string>(); var dict2 = dict1; Console.WriteLine(dict1.Equals(dict2)); // Output: True
Time Complexity : O(1) , Reference comparison is constant time.
Use Case : Use Equals to check if two variables refer to the same dictionary object, not for checking if contents are identical.
7. GetEnumerator()
The GetEnumerator() method returns an enumerator that allows you to iterate over all key-value pairs in a Dictionary<TKey, TValue>. In C#, this is usually used implicitly with a foreach loop.
var enumerator = dict.GetEnumerator();
while (enumerator.MoveNext())
{
var kvp = enumerator.Current;
Console.WriteLine($"{kvp.Key} = {kvp.Value}");
}Time Complexity : O(n) , Iterates through all n elements.
Use Case- Use GetEnumerator() to loop through all dictionary entries efficiently.
- Typically used in foreach, but can also be used explicitly if you need manual control over iteration.
8. GetHashCode()
GetHashCode() returns a hash code for the current Dictionary<TKey, TValue> instance. It is mostly used internally by .NET for hash-based collections and comparisons, rather than for manual operations.
dict.GetHashCode()
Time Complexity : O(1) , Returns the hash code of the dictionary instance.
Use Case- Rarely needed in regular coding.
- Primarily used by the runtime to identify objects in hash-based structures like HashSet or as a key in another dictionary.
9. GetType()
GetType() returns the runtime type of the dictionary instance. This is useful for reflection, type checks or debugging.
var dict = new Dictionary<int, string>(); Console.WriteLine(dict.GetType());
System.Collections.Generic.Dictionary`2[System.Int32,System.String]
Time Complexity : O(1) , Retrieving the type is a constant-time operation.
Use Case- To determine the exact runtime type of a dictionary.
- Useful in reflection, logging or when working with generic collections dynamically.
10. Remove(TKey)
Remove(TKey) deletes the key-value pair with the specified key from the dictionary. Returns true if the key was found and removed otherwise, false.
dict.Remove(i);
- O(1) on average : Dictionary uses a hash table for quick key lookup.
- Worst case: O(n) if many keys collide (rare).
Use Remove to delete an entry safely without throwing an exception if the key doesn’t exist.
11. Remove(TKey, TValue)
Remove(TKey, TValue) removes the key-value pair only if both the key and its associated value match. Returns true if the pair was found and removed, otherwise false.
dict.Remove(i, x);
- O(1) on average : Hash table lookup.
- Worst case O(n) in rare collisions.
- Use when you want to ensure both key and value match before removing an entry.
- Safer for scenarios where the value might have changed and you don’t want accidental deletions.
12. TryAdd(TKey, TValue)
TryAdd attempts to add a new key-value pair to the dictionary. It does not overwrite an existing key. Returns true if the pair was added successfully, otherwise false.
dict.TryAdd(i, x); // Safe add
- O(1) on average , hash table lookup to check the key.
- Worst case: O(n) in rare collisions.
- Use TryAdd when you want to add an entry only if the key does not exist, preventing accidental overwrites.
13. TryGetValue(TKey, out TValue)
TryGetValue attempts to retrieve the value associated with a specified key
- Returns true if the key exists, and outputs the value via out.
- Returns false if the key does not exist, and sets out to the default value.
- Safe alternative to accessing a key directly with the indexer, which throws an exception if the key is missing.
if (dict.TryGetValue(1, out string name))
Console.WriteLine("Value: " + name);
else
Console.WriteLine("Key not found");- O(1) on average : hash table lookup.
- Worst case: O(n) in rare collisions.
- Use TryGetValue for safe, efficient retrieval when you’re not sure if the key exists, avoiding exceptions
14. TrimExcess() and TrimExcess(Int32)
- TrimExcess() reduces the internal storage of a dictionary to match the current number of elements, freeing unused memory.
- TrimExcess(int capacity) ensures the dictionary can hold at least the specified capacity without unnecessary overhead.
- Useful for memory optimization after bulk additions or deletions.
var dict = new Dictionary<int, string>(1000); // Large initial capacity dict.Add(1, "Apple"); dict.Add(2, "Mango"); // Trim excess memory dict.TrimExcess(); // Optional: ensure a specific capacity dict.TrimExcess(500);
Time Complexity : O(n) , Copies existing elements into a new internal array when resizing occurs.
Use Case- Reduce memory usage after adding and removing many elements.
- Optimize dictionaries that grow dynamically but won’t need full allocated space anymore.
15. ToString()
ToString() returns a string representation of the dictionary object.
dict.ToString();
Useful for logging or debugging to check the type of the dictionary.
Final Thoughts
The Dictionary<TKey, TValue> class is one of the most efficient and versatile data structures in C#. By understanding its properties, methods and internal working, you can design code that’s not just functional but also highly optimized for speed and scalability.
Whether you’re building small utilities, backend services or high-performance systems mastering Dictionary is essential for writing clean, efficient and professional-grade C# code.
