Programming Stuff

Dictionary ContainsKey() vs TryGetValue()

Using TryGetValue() to check if a key exists or not in a dictionary can improve performance of your application.

Check the fallow example, MyClass, where we required to create one instance for id/key: (Factory Pattern)

May the way you design, looks like this:

A more efficient way is by using TryGetValue()

If a program frequently tries key values that are not in a dictionary, the TryGetValue method can be more efficient than using the Item property (the indexer in C#), which throws exceptions when attempting to retrieve nonexistent keys.

Attempts to get the value using Try/Catch could also have a good performance since there is not loop through the Dictionary, but still I prefer use TryGetValue().

For more information checks out:

IDictionary<TKey, TValue>.ContainsKey Method http://msdn.microsoft.com/en-us/library/htszx2dy.aspx

IDictionary<TKey, TValue>.TryGetValue Method http://msdn.microsoft.com/en-us/library/bb299639.aspx

Big O notation http://en.wikipedia.org/wiki/Big_O_notation