Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the .NET Dictionary<TKey, TValue> immutable?

Tags:

c#

.net

I declared a Dictionary type object and try to add some items into it. But I cannot modify even the value of the item. It's reasonable that key should not be modifiable, but why not the value? Thanks.

    Dictionary<string, string> dict = new Dictionary<string, string>();
    dict.Add("1", "bob");
    dict.Add("2", "jack");
    dict.Add("3", "wtf");
    foreach (string key in dict.Keys)
    {
        dict[key] = "changed"; //System.InvalidOperationException: Collection was modified
    }
like image 652
smwikipedia Avatar asked Nov 15 '10 10:11

smwikipedia


People also ask

Are Dictionaries immutable C#?

Values can be any type of object, but keys must be immutable. This means keys could be integers, strings, or tuples, but not lists, because lists are mutable. Dictionaries themselves are mutable, so entries can be added, removed, and changed at any time.

What is TKey and TValue?

In Dictionary<TKey,TValue> TKey is the type of the Key, and TValue is the Type of the Value. It is recommended that you use a similar naming convention if possible in your own generics when there is nore than one type parameter.

What is TKey and TValue in C#?

The Dictionary<TKey, TValue> Class in C# is a collection of Keys and Values. It is a generic collection class in the System. Collections. Generic namespace. The Dictionary <TKey, TValue> generic class provides a mapping from a set of keys to a set of values.

Is dictionary mutable C#?

The ImmutableDictionary<TKey,TValue> class represents an immutable, unordered collection of keys and values in C#. However, you can't create an immutable dictionary with the standard initializer syntax, since the compiler internally translates each key/value pair into chains of the Add() method.


1 Answers

You are not allowed to modify the collection you are iterating over in a foreach loop. This has nothing to do with the dictionary - dict[key] = "value"; works perfectly fine outside foreach loops.

like image 84
Femaref Avatar answered Oct 06 '22 20:10

Femaref