λ0001: Disallowed use of TryGetValue
TryGetValue
should not be used.
Cause
TryGetValue
is used outside one of the allowed use cases.
Reason for rule
TryGetValue
is an advanced API that is needed to interoperate with imperative constructs, such as loops and catch
filter clauses.
Use of this API is restricted to prevent misuse. This is critical since TryGetValue
is essentially a function to get the value out of the option.
How to fix violations
Use one of the functions provided on Option<T>
such as Select
, SelectMany
, Match
or GetOrElse
.
Examples
Disallowed
static void Example(Option<int> option)
{
const int fallback = 42;
var valueOrFallback = option.TryGetValue(out var value) ? value : fallback;
}
Allowed
Iterator
public static IEnumerable<TItem> Successors<TItem>(Option<TItem> first, Func<TItem, Option<TItem>> successor)
where TItem : notnull
{
var item = first;
while (item.TryGetValue(out var itemValue))
{
yield return itemValue;
item = successor(itemValue);
}
}
Catch filter clause
try
{
// ...
} catch (Exception exception) when (FindHandlerForException(exception).TryGetValue(out var handler))
{
handler.Handle(exception);
}
Option<IExceptionHandler> FindHandlerForException(Exception exception) => ...;