Skip to content

Dictionary TryGetValue(TKey, TValue) - Unhandled exception. #81357

Answered by koszeggy
Was85 asked this question in General
Discussion options

You must be logged in to vote

I believe this should be changed

Modifying this behavior would be a breaking change. And considering that keys cannot be null this behavior makes sense.

But you can always define a new extension method, eg.

public static bool MyTryGetValue<TKey, TValue>(this IDictionary<TKey, TValue> dict,
    TKey key, [MaybeNullWhen(false)]out TValue value)
{
    if (key == null)
    {
        value = default;
        return false;
    }

    return dict.TryGetValue(key, out value);
}

And just a side note: I needed to create an AllowNullDictionary type once. But please note that its TryGetValue explicitly contains a [CanBeNull] attribute for the key parameter, which triggered CS8767 (Nullability of re…

Replies: 0 comments 2 replies

Comment options

You must be logged in to vote
0 replies
Answer selected by Was85
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants