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...
Understanding and Using ? (nullable) in C# In C#, ? is the symbol used to declare a variable as nullable, meaning it can hold a null value. ? (nullable) declaration string text1 = null; string? text2 = null; Both variables are null , but when you call text1.ToString() , a runtime null reference exception will occur. This happens because text1 is null , meaning it points to nothing. Trying to access .ToString() on a null variable results in an exception. To put it into words, asking someone who has no thoughts, "What should we have for lunch?" is similar. The person doesn't have any thoughts, so asking them anything at all would be an error. On the other hand, text2 has been declared with ? , which tells the compiler, "This variable might be null ." However, just informing the compiler doesn't automatically prevent exceptions. You still need to handle it explicitly. ?. (null-conditional operator) Thus, ? ...