3 ms·
Out parameters are bad, even with the improvements in C# 7. They're simply the Wrong Way to do multiple return values. I agree, but I fear that even with the n
by btschaegg 10y ago
Out parameters are bad, even with the improvements in C# 7. They're simply the Wrong Way to do multiple return values.
I agree, but I fear that even with the new features, the according APIs will be missing for a considerable amount of time. It constantly surprises me is that MS has never bothered to update their old APIs with more modern methods; especally where out parameters are used for optional return values.
In almost all my projects I have extension methods like this:
public static V TryGetValue<K,V>(this IReadOnlyDictionary<K,V> dict, K key, V @default = default(V))
{
if (dict == null)
throw new ArgumentNullException(nameof(dict));
V result = default(V);
if (!dict.TryGetValue(key, out result))
return @default;
return result;
}
There is a considerable number of existing methods that would lead to sooo much nicer code if there would be some versions using modern C# features. In the case above, you can still use the original TryGetValue if there's no usable sentinel value you can use to distinguish "not found" cases from success.
There are also a lot of old methods using Type arguments and requiring a cast where a generic alternative is really overdue.
Edit: Of course, some Optional<T> type would also be nice for the dictionary example, but since C# has null-coalescing and null-conditionals since version 5/6, the above example suits almost all my use cases, and can be used in a Maybe Monad-style way anyway.