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
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With