Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Collections

IDictionary and IReadOnlyDictionary

Reference for C# IDictionary<TKey,TValue> and IReadOnlyDictionary<TKey,TValue>: members, which classes implement them, TryGetValue and choosing a parameter type.

IDictionary<TKey,TValue> is the interface for "look up a value by key" collections. Dictionary, SortedDictionary, SortedList and ConcurrentDictionary all implement it (as does ExpandoObject). It extends ICollection<KeyValuePair<TKey,TValue>>, so you can also enumerate it as key-value pairs.

IReadOnlyDictionary<TKey,TValue> (.NET 4.5) is the read-only counterpart: lookups, Keys, Values, ContainsKey and TryGetValue, but no way to add or remove. Use it for parameters and return values that must not be modified through that reference.

C#
IDictionary<string, int> ages = new Dictionary<string, int>();
ages["Ana"] = 31;
ages.TryGetValue("Ana", out int age);

Try it

C# Programming against IDictionary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Read-only access

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public interface IDictionary<TKey, TValue>
    : ICollection<KeyValuePair<TKey, TValue>>
{
    TValue this[TKey key] { get; set; }
    ICollection<TKey> Keys { get; }
    ICollection<TValue> Values { get; }
    void Add(TKey key, TValue value);
    bool ContainsKey(TKey key);
    bool Remove(TKey key);
    bool TryGetValue(TKey key, out TValue value);
}

public interface IReadOnlyDictionary<TKey, TValue>
    : IReadOnlyCollection<KeyValuePair<TKey, TValue>>
{
    TValue this[TKey key] { get; }
    IEnumerable<TKey> Keys { get; }
    IEnumerable<TValue> Values { get; }
    bool ContainsKey(TKey key);
    bool TryGetValue(TKey key, out TValue value);
}
Name Description
key The lookup key. null is not allowed for Dictionary.
Keys, Values The keys and values, in the dictionary's own enumeration order.
TryGetValue Looks up without throwing. When the key is missing, value is default.

Returns: Remove(key) is true if something was removed. ContainsKey and TryGetValue return bool.

Errors: the indexer getter throws KeyNotFoundException; Add throws ArgumentException for a duplicate key; a null key throws ArgumentNullException. A dictionary created read-only throws NotSupportedException on writes.

Usage notes

  • Indexer set versus Add. d[k] = v adds or overwrites; d.Add(k, v) throws if the key exists. On ConcurrentDictionary, use the dedicated atomic methods instead.
  • TryGetValue does one lookup. if (d.ContainsKey(k)) use(d[k]) does two. Prefer TryGetValue.
  • Interface versus class Keys. IDictionary.Keys is an ICollection<TKey> (with Count, Contains); IReadOnlyDictionary.Keys is only an IEnumerable<TKey>. A Dictionary has Keys of its own KeyCollection type, a live view with no copying.
  • Two interfaces, one class. Dictionary<K,V> implements both, but IDictionary<K,V> does not inherit IReadOnlyDictionary<K,V>. A method that takes IReadOnlyDictionary therefore cannot receive an IDictionary variable without a cast or copy, and some collections (like ImmutableDictionary) implement only the read-only one.
  • Order depends on the class. Dictionary has no promised order; SortedDictionary is sorted by key. Do not rely on insertion order.
  • Missing-key helpers. GetValueOrDefault, TryAdd and CollectionExtensions methods work on the interfaces (TryAdd for IDictionary, GetValueOrDefault for both). See Dictionary operations.
  • Not thread-safe except ConcurrentDictionary.