Using Dictionary.TryGetValue() in dictionary lookups

From my understanding using TryGetValue(key, out object) will be “cheaper” than what is given in the lectures as it searches once, returns true if it exists and grabs the value associated with the key for you to use. This means that it only has to search the dictionary once rather than what the lecture suggests which is
if ( // key exists)
dictionary[key] = // do something
which is at least searching the dictionary twice.
Am I correct in this logic?

You’ll find a lot of debate on this, but It’s actually a wash… Here’s the source for TryGetValue()

        public bool TryGetValue(TKey key, out TValue value) {
            int i = FindEntry(key);
            if (i >= 0) {
                value = entries[i].value;
                return true;
            }
            value = default(TValue);
            return false;
        }

https://referencesource.microsoft.com/#mscorlib/system/collections/generic/dictionary.cs,2e5bc6d8c0f21e67

Privacy & Terms