mono / sharpen

Sharpen is an Eclipse plugin created by db4o that allows you to convert your Java project into c#
GNU General Public License v2.0
381 stars 141 forks source link

Dictionary get indexer used incorrectly #75

Open sharwell opened 8 years ago

sharwell commented 8 years ago

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 commented 7 years ago

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 commented 4 years ago

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