Skip to content

Commit

Permalink
Add Dictionary<TKey,TValue>.TryAdd(TKey, TValue) method
Browse files Browse the repository at this point in the history
  • Loading branch information
stephentoub committed Jun 7, 2015
1 parent 1bb4f3a commit b3b0ba4
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions src/mscorlib/src/System/Collections/Generic/Dictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,14 @@ public TValue this[TKey key] {
}

public void Add(TKey key, TValue value) {
Insert(key, value, true);
if (!TryAdd(key, value)) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
}
}

public bool TryAdd(TKey key, TValue value)
{
return Insert(key, value, true);
}

void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) {
Expand Down Expand Up @@ -313,7 +320,8 @@ private void Initialize(int capacity) {
freeList = -1;
}

private void Insert(TKey key, TValue value, bool add) {
// returns false if the key already existed in the collection, or true if it didn't
private bool Insert(TKey key, TValue value, bool add) {

if( key == null ) {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
Expand All @@ -329,12 +337,12 @@ private void Insert(TKey key, TValue value, bool add) {

for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next) {
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) {
if (add) {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
if (!add)
{
entries[i].value = value;
version++;
}
entries[i].value = value;
version++;
return;
return false;
}

#if FEATURE_RANDOMIZED_STRING_HASHING
Expand Down Expand Up @@ -386,6 +394,7 @@ private void Insert(TKey key, TValue value, bool add) {
#endif // FEATURE_CORECLR

#endif
return true;

}

Expand Down Expand Up @@ -422,7 +431,7 @@ public virtual void OnDeserialization(Object sender) {
if ( array[i].Key == null) {
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey);
}
Insert(array[i].Key, array[i].Value, true);
Add(array[i].Key, array[i].Value);
}
}
else {
Expand Down

0 comments on commit b3b0ba4

Please sign in to comment.