Using a string as a hastables key

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
 
B

Bob Grommes

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
 
L

Lloyd Dupont

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>
 
A

Adam Calderon (MCSD, MCAD, MCP)

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top