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

IDictionary<TKey, TValue>.TryGetValue Method

Big O notation