5

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.

Kev
  • 118,037
  • 53
  • 300
  • 385

3 Answers3

7

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
  • 161,458
  • 45
  • 265
  • 341
7

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.

  • 1
    Only the `GetHashCode` value and the equivalence class defined by `Equals` need to be immutable. Note that a suitable equivalence class is defined for all class types--reference equality--and indeed that is generally the only equivalence class which should be used for mutable objects. There is nothing whatsoever wrong with having a mutable class type as a dictionary key if the purpose of the dictionary is to associate instances of that type with something else. – supercat Sep 12 '12 at 20:53
3

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:

C# Dictionary<> and mutable keys

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

Community
  • 1
  • 1
code4life
  • 15,655
  • 7
  • 50
  • 82