Painfully obvious/non-obvious things...

So I spent 10 minutes yesterday looking in Help and Google searching for a way to access the value in a Hashtable object by its key. I've done it before, and I'm not stupid about these things, and its embarassing, frankly.

The Help tells you how to add stuff to the Hashtable (ie. myHashTable.Add(key, value)) and see if the key is in the hash table (myHashTable.ContainsKey(testkey)), but it doesn't show you in the examples how to get the actual value out. There is the Keys and Values collections that you can iterate through, but I know there's an easier way than that.

Finally I'm back to VS.NET and the Intellisense and I'm thinking “ok, it must be some sort of array-like accessor, maybe a ( ...? nope. maybe a [ ...  aha! that's it!“).

if (myHashtable.ContainsKey(myKey))
{
  
myValue = (string)myHashtable[myKey]; 
}

Hooray for Intellisense.

That's 10 minutes I'll never get back. And now the three people who might read my blog knows that sometimes I feel like a complete idiot.

5 Comments

  • I have found that a lot of simple things are like that, it is almost impossibe to find real basic instructions.



    In my first explorations of c#, I had trouble declaring arrays. I would keep typing "new Array(" and then ... well I'm sure you know the feeling.

  • I think we all have those days...

  • It would be more efficient to write the code like this:



    <codeSnippet language="C#">

    myValue = (string)myHashtable[myKey];



    if(myValue != null)

    {

    ... work with it here ...

    }

    </codeSnippet>



    The reason for this is that it reduces the number of lookups. In your example, you're doing two lookups: ContainsKey and then the indexer. In my code, you're doing one lookup and then testing the result which, if the dictionary doesn't contain the key, will be null.



  • Hmm, interesting. I guess I had it in my head that attempting to index the hashtable on a non-existent key would throw an Exception. Is that the "old VB6" way? Something in my brain is telling me that.



    Thanks for the opimization.



    Mike

  • I admit I spent half an hour looking for the same thing. I was looking for a 'get' method! I feel accessing should be included in code snippet in the help.

Comments have been disabled for this content.