-
Notifications
You must be signed in to change notification settings - Fork 15
IDictionaryExtensions
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:
- 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.
- If, for example, the dictionary's values are of type
int
and0
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)
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.
Action
/Func
conversionsCycle
methods- Converting between
Action
andFunc
- Extension methods for existing types that use
Option<T>
- Indexed enumerations
IEnumerable<T>
cons- Option-based parsers
- Partial function applications
- Pattern matching
- Pipe Operators
- Typed lambdas
Any
Either<TLeft,TRight>
None
Option<T>
Success<T>
Union<T1,T2>
Union<T1,T2,T3>
Union<T1,T2,T3,T4>
Unit
ValueOrError