Using a string as a hastables key

  • Thread starter Thread starter thechaosengine
  • Start date Start date
T

thechaosengine

Hi all,

Is it ok to use a string as the key for Hashtable entries? I want to use
the name of entity in question, which I know will always be unique.
Do I have to do anything fancy equality-wise or are there any caveats I should

be aware of?

Thanks to anyone who can advise.

Kindest Regards

tce
 
No problem at all.

In System.Collections.Specialized is a StringDictionary class that may be
useful to you in this scenario. It is a wrapper around Hashtable to enforce
that keys must be strings.

--Bob
 
the potential caveat about keys are the following:
- changing value hence changing Hashcode() or Equals() result

string are immutable therefore excellent candidate

in .NET 2.0 you could also use
Dictionary<string, MyType>
 
If you really want to make sure your code is reliable put some
checking in place before you add the entry.

StringDictionary stringDic = new StringDictionary();
string stringKey = "FirstOne";
stringDic.Add(stringKey,"One");

//comment out below and an error occurs
//stringDic.Add(stringKey,"Two");

//in your code before you add your entry check to see if it exists
if(stringDic.ContainsKey(stringKey) = false)
{
stringDic.Add(stringKey,"Two");
}


- Adam
 
Back
Top