Tuesday, February 10, 2015

How to use a dictionary wisely

A dictionary is a touchy object - if you try to access a non-existant key, you get an exception. If you try to add an item using the Add() method which already exists in the dictionary - you get an exception. So, particularly in a multi-threaded environment, it is worth knowing some dictionary tricks
1. If you want to retrieve an item which may not be in the dictionary, use TryGetValue() method. This way you access the dictionary only once, but accomplish 2 things - you get the item if it exists, or safely know that it doesn't. The alternative - using ContainsKey() method and then accesing the item directly using its key - is not as good, because it envolves accessing the dictionary twice - once to check if the key exists, and second to get the item. And, if the item has been removed between these two actions - you get an exception on the second action of retrieving the item.
2. When you want to add an item to the dictionary, don't use the Add() method, use the indexer. Add() throws an exception if the item already exists, and usually (not always) this is not desirable. So, do this: dict[key] = value; This way, if the item exists, it is silently overriden.

Also note, in multi-threading environment which includes any add/remove operations, any access to the dictionary, including read operations, must be protected with a lock, as Dictionary is not thread-safe and a read operation which happens at the same time as an add/remove operation may encounter an exception. In any multi-threading context, consider using ConcurrentDictionary class.

Adam Porat is a senior c# developer at Travolutionary.

No comments:

Post a Comment