Retrieving Dictionary Value Best Practices

TryGetValue is slightly faster, because FindEntry will only be called once.

How much faster? It depends on the
dataset at hand. When you call the
Contains method, Dictionary does an
internal search to find its index. If
it returns true, you need another
index search to get the actual value.
When you use TryGetValue, it searches
only once for the index and if found,
it assigns the value to your variable.

FYI: It’s not actually catching an error.

It’s calling:

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

ContainsKey is this:

public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}

Leave a Comment