Skip to content
This repository has been archived by the owner on Mar 9, 2021. It is now read-only.

Dictionary get indexer used incorrectly #75

Open
sharwell opened this issue Jun 8, 2016 · 2 comments
Open

Dictionary get indexer used incorrectly #75

sharwell opened this issue Jun 8, 2016 · 2 comments

Comments

@sharwell
Copy link
Contributor

sharwell commented Jun 8, 2016

In Java, Map.get returns null when an element does not exist. In C#, the get indexer for IDictionary<TKey, TValue> throws an exception in the same scenario. Currently calls to get are getting translated into indexer usage, but this breaks the semantics for this operation. The correct code for this case would be the following:

Java:

T value = map.get(key);

C#:

T value;
map.TryGetValue(key, out value);
@hazzik
Copy link
Contributor

hazzik commented Jun 1, 2017

These are not equivalent as map.get(key) is an expression and

T value;
map.TryGetValue(key, out value);

Is a statement block. The correct way would be to map this operation to the following extension method:

public V TryGet<K, V>(this IDictionarry<K,V> map, K key) 
{
    V value;
    map.TryGetValue(key);
    return value;
}

@fubar-coder
Copy link

Or in latest C#: map.TryGetValue(key, out var value) ? value : default(T)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants