There’re no associative arrays (hash) in common sense. There are Dictionaries for this. It’s a very good tool if you want to use link "key-value". Using Dictionaries, keys and values can be different types.

For creating associative array in C# you should initialize IDictionary and set types for keys and values:

The result is:

Figure 1

Figure 1

Keys in IDictionary must be unique. If you try to add element with the existing key (for example, if you add string "arrayStat.Add("green", 20);" ), you will get the error:

Unhandled Exception: System.ArgumentException: An item with the same key has already been added.   at System.Collections.Generic.Dictionary '2.Insert(TKey key, TValue value, Boolean add)    at dicts.Program.Main(String[] args) in c:\Projects\Visual Studio 2013\Projects\dicts\dicts\Program.cs:line 19

 

If you fill IDictionary manually, I don’t think you see this error. But if you work with database results or calculations, it’s easy to get this error.

Let’s try to add keys-values to IDictionary from List.

We have a class SimpleClass:

Let’s initialize List<SimpleClass> and add values to it:

Now let’s fill IDictionary from List<SimpleClass>:

 

The result is expectable:

Figure 2

Figure 2

Now let’s modify collection List<SipleClass> and build and execute program:

 

Again we have error:

Unhandled Exception: System.ArgumentException: An item with the same key has already been added.   at System.Collections.Generic.Dictionary '2.Insert(TKey key, TValue value, Boolean add)   at dicts.Program.Main(String[] args) in c:\Projects\Visual Studio 2013\Projects\dicts\dicts\Program.cs:line 42

 

The error is in "arrayStat.Add(item.Color, item.quantity);". To fix the error, you need to check if the key already exists.

 

Summary:

Initialize IDictionary:

IDictionary<string, int> arrayStat = new Dictionary<string, int>();

 

Add item to IDictionary:

arrayStat.Add(key, value);

 

Update item to IDictionary:

arrayStat[key] = value;