Skip to content

IDictionaryExtensions

David Arno edited this page Feb 17, 2020 · 2 revisions

IDictionary<T> Extension methods using Option<T>

Succinc<T> alternative to TryGetValue


Introduction to Succinc<T>'s IDictionary<T> extension methods

IDictionary<T> provides a method, TryGetValue, that either returns the value held by the specified key, or returns the type's default value if that key doesn't exist. This method suffer from two problems:

  1. If the type of the value is a reference type, then the default value is null. This forces the developer into handling cases where the method returns null, preventing method chaining for example.
  2. If, for example, the dictionary's values are of type int and 0 is returned, the developer has no way of knowing whether that's because the key held that value, or that the key doesn't exist.

Both cases are code smells: they are potential problems that the developer must guard against with defensive code: checking for null and testing if the key exists, respectively.

Succinc<T> provides an alternative to this methods by returning an Option<T>. If the key exists, then its value is returned; otherwise none is returned. This addresses both of the above smells.

(For more details on interacting with the returned option, see the Option<T> page)

TryGetValue

public static Option<TValue> TryGetValue<TKey, TValue>(
    this IDictionary<TKey, TValue> dictionary,
    TKey key)

If key exists in the dictionary, Some<T> will be returned, containing the value held by that key. Otherwise none is returned.

Clone this wiki locally