Thursday, February 25, 2010

dotNet Dictionary - ContainsKey

I think Dictionary objects are brilliant data structures. The way they can contain objects and nested dictionaries within them seleves makes them a fantasic store,

However I was using a Dictionary obect to store Key Value Pairs and I couldnt be sure that I knew if all the key's were present. The first way I found to check was to try to get the key within a Try Catch block and if they key wasnt found the Catch block would return a default value.

This was both stressfull to me and the performance of the app, so I was very pleased when I found a method to test if a key existed: Dictionary<(Of <(TKey, TValue>)>)..::.ContainsKey Method

BUT I was even happier when I found the Dictionary<(Of <(TKey, TValue>)>)..::.TryGetValue Method

TryGetValue means you dont need to wrap your code in Try Catch blocks to handle exceptions and you can pass back a default value if the key is not found. Brilliant !

No comments: