8

In .NET can I use any string as a dictionary key? This is part of a templating engine and I'm planning allow users to add their custom headers and values.

Headers will be something like "Value of X" or "Summary of Analyse & XYZ Reports", I'm worried if they would get an exception in a rare character or something like that.

I assume there size limit but expecting it to be larger than 256 characters. MSDN hasn't got any details on the subject.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
dr. evil
  • 26,944
  • 33
  • 131
  • 201

3 Answers3

10

The dictionary doesn't have any special knowledge of the types used as its keys and values. Irrespective of the object type it will simply call the GetHashCode and Equals methods to allow it to put the value in the right bucket and retrieve it again. Which means that any class which correctly implements these methods can be used as the key.

The string class does correctly implement these methods based on its value, so as long as you can construct an instance of the string, then you can use it as the key.

Greg Beech
  • 133,383
  • 43
  • 204
  • 250
  • If no other comparator is specified, the constructor for Dictionary(of T,U) will check whether type T implements iEquatable(of T). If so, keys will be compared using iEquatable(of T).Equals rather than Object.Equals. Generally, this won't batter, but if an inheritable class implements iEquatable(of itsType), any class with different comparison semantics which is derived from it must re-implement iEquatable(of theEarlierType) or erroneous results may occur. – supercat Nov 26 '10 at 22:46
7

Yes, it can use any valid string (which is limited to a couple billion bytes).

BTW, you might pass a custom IEqualityComparer<T> that you might pass to the Dictionary constructor which might require a maximum limit.

Dmitri Nesteruk
  • 23,067
  • 22
  • 97
  • 166
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
2

Since the key is just a .NET string, see this related SO question: What is the maximum possible length of a .NET string?

Community
  • 1
  • 1
Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541