From b3b0ba4c6d9ffc2e400cbb9c86b6d1ec86125833 Mon Sep 17 00:00:00 2001 From: stephentoub Date: Sun, 7 Jun 2015 07:56:56 -0400 Subject: [PATCH] Add Dictionary.TryAdd(TKey, TValue) method --- .../System/Collections/Generic/Dictionary.cs | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs index 08621485f404..2626476b8d9b 100644 --- a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs +++ b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs @@ -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>.Add(KeyValuePair keyValuePair) { @@ -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); @@ -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 @@ -386,6 +394,7 @@ private void Insert(TKey key, TValue value, bool add) { #endif // FEATURE_CORECLR #endif + return true; } @@ -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 {