Common Mistakes When Using Dictionary Like an Array in C#
Get link
Facebook
X
Pinterest
Email
Other Apps
Common Mistakes When Using Dictionary Like an Array in C#
Why treating Dictionary like an array leads to errors
In C#, a Dictionary uses square bracket syntax (like dict[key]), which might lead you to believe it works like an array. However, this is misleading. If you attempt to use a for loop with an index, you’ll run into runtime errors.
Here's an example:
Dictionary<int, string> numbers = new Dictionary<int, string>()
{
{ 1, "one" },
{ 20, "twenty" },
{ 3, "three" },
{ 19, "nineteen" },
{ 5, "five" },
};
for (int i = 0; i < numbers.Count; i++)
{
if (numbers[i] == "five")
{
Console.WriteLine(numbers[i]);
break;
}
Console.WriteLine(numbers[i]);
}
This code throws the following error:
The given key '0' was not present in the dictionary.
Why? Because the dictionary has keys 1, 20, 3, 19, and 5 — not 0 through 4.
Dictionary is not an array
The syntax dict[key] looks like an array index, but it actually uses the C# feature called indexers. These allow object access via square brackets, but under the hood, it's a method call like this[key], not memory-based indexing like in an array.
Therefore, trying to loop from 0 to Count is meaningless unless your keys happen to be 0-based integers, which is rarely the case.
The right way to iterate over a Dictionary
Instead of using a for loop, you should use foreach to iterate over the dictionary:
Another point to remember is that dictionaries do not preserve insertion order.
Even if you add items in a specific sequence, the output order may be completely different. This is because dictionaries store items based on the hash code of the keys, not on their position.
How hash table and collisions work internally
When you insert a key into a dictionary, it is converted into a hash value. That hash determines where in the internal structure the item is stored.
If multiple keys result in the same hash bucket (a hash collision), the dictionary forms a chain using a singly linked list internally. This happens under the hood and is handled automatically — you don't need to worry about it as a developer.
Summary
Dictionary[key] accesses a value by key, not by index like an array.
Using for (int i = 0; i < dict.Count; i++) is not safe unless your keys are sequential integers.
foreach is the correct way to iterate over dictionaries.
Dictionaries do not guarantee order — they are optimized for fast lookup, not sequential storage.
Internally, dictionaries use hash tables with automatic collision handling using linked structures.
If you’ve been thinking of Dictionary as a fancier array, now’s the time to stop — it’s a very different tool, designed for different needs.
Arrays as Reference Types In programming, it's important to understand the behavior of arrays. In most programming languages including C#, arrays are treated as reference types. This article will explore what that means and how to use that knowledge effectively. Value Types vs Reference Types In C#, data types are categorized into two main types: Value types : Store actual values directly. Examples : int , float , bool , struct Reference types : Store memory addresses instead of the actual values. Examples: class , string , array , delegate Arrays, like classes, are reference types. When you assign one array variable to another, you're copying the reference, not the actual data. Example: Arrays as Reference Types using System; class Program { static void Main() { int[] array1 = { 1, 2, 3 }; int[] array2 = array1; // Copy reference array2[0] = 100; Console.WriteLine(array1[0]); // Out...
Setting Up a Basic Follow Camera with Cinemachine 3.x Cinemachine has been significantly upgraded in version 3.x, introducing new concepts, improved terminology, and a refined workflow. In this post, we’ll go through how to set up a simple follow camera using the latest version. For more advanced examples, be sure to check out the sample scenes provided in the Cinemachine package—they’re very helpful for understanding the system. Install the Cinemachine Package Start by downloading and importing the Cinemachine package from the Unity Package Manager. Check the Main Camera After installation, you'll notice that the Main Camera now has a Cinemachine Brain component attached. Make sure the Live Camera field shows the name of your Cinemachine Camera. Create a Cinemachine Camera In the Hierarchy window, right-click and go to Cinemachine > Cinemachine Camera to create a new virtual camera. Set the Tracking Targe...
How to Initialize Struct – C# Struct Initialization Guide In C#, there are multiple ways to declare and initialize structs. While using just one method is often enough, it's common to encounter different initialization styles in real-world code. This guide summarizes the most common approaches, including how to handle struct arrays and lists. Struct Declaration struct Item { public string name; public int price; public string desc; } 1. Declare First, Assign Later This is the most straightforward method. Declare the struct first, then assign values to its fields one by one. Item item; item.name = "Fireball"; item.price = 100; item.desc = "Deals fire damage to the enemy."; Note: Structs are value types, so you can declare them without new . However, you must initialize all fields before use, or you'll get a compile-time error. 2. Use new and Assign Fields Item item = new Item(); item.name = "Fir...