views:

87

answers:

3

I get a Dictionary<string, string> back from an API but depending on certain rules need to modify some of the key names.

Before I head down the road of copying to a new Dictionary I just wanted to confirm that the keys in a Dictionary<TKey, TValue> are immutable.

+7  A: 

You are right, if the key changes, you will need to remove the entry with the old key and insert a new entry with the new key.

If only some of the keys change, you don't need to copy the entire dictionary. Both Add and Remove operations on Dictionary are roughly O(1) operations.

driis
+2  A: 

The keys in a Dictionary<string, string> are immutable.

For instance, the following code:

Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("One", "1");
dict.Add("Two", "2");

var k = dict.First();
k.Key = "Three";

Will throw the following compiler error:

Property or indexer 'System.Collections.Generic.KeyValuePair.Key' cannot be assigned to -- it is read only

That being said, a Dictionary<T, T> may have mutable keys if you use a reference type, see:

http://stackoverflow.com/questions/3007296/c-dictionary-and-mutable-keys

(I know, I know, strings are reference types... but the link above will explain...)

code4life
+4  A: 

It is more like that you have to make sure that the type you use for TKey is immutable if it is a reference type. String is immutable, by the way. Value types can be mutable, but you don't get the opportunity to modify the stored key in the Dictionary.

jdv
+1 for actually answering the question. ;)
Kirk Woll