using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
+ /// <summary>
+ /// Used internally to control behavior of insertion into a <see cref="Dictionary{TKey, TValue}"/>.
+ /// </summary>
+ internal enum InsertionBehavior : byte
+ {
+ /// <summary>
+ /// The default insertion behavior.
+ /// </summary>
+ None = 0,
+
+ /// <summary>
+ /// Specifies that an existing entry with the same key should be overwritten if encountered.
+ /// </summary>
+ OverwriteExisting = 1,
+
+ /// <summary>
+ /// Specifies that if an existing entry with the same key is encountered, an exception should be thrown.
+ /// </summary>
+ ThrowOnExisting = 2
+ }
+
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
}
set
{
- Insert(key, value, false);
+ bool modified = TryInsert(key, value, InsertionBehavior.OverwriteExisting);
+ Debug.Assert(modified);
}
}
public void Add(TKey key, TValue value)
{
- Insert(key, value, true);
+ bool modified = TryInsert(key, value, InsertionBehavior.ThrowOnExisting);
+ Debug.Assert(modified); // If there was an existing key and the Add failed, an exception will already have been thrown.
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
freeList = -1;
}
- private void Insert(TKey key, TValue value, bool add)
+ private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior)
{
if (key == null)
{
{
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
{
- if (add)
+ if (behavior == InsertionBehavior.OverwriteExisting)
+ {
+ entries[i].value = value;
+ version++;
+ return true;
+ }
+
+ if (behavior == InsertionBehavior.ThrowOnExisting)
{
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
}
- entries[i].value = value;
- version++;
- return;
+
+ return false;
}
#if FEATURE_RANDOMIZED_STRING_HASHING
}
#endif
+ return true;
}
public virtual void OnDeserialization(Object sender)
{
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey);
}
- Insert(array[i].Key, array[i].Value, true);
+ Add(array[i].Key, array[i].Value);
}
}
else
return defaultValue;
}
+ public bool TryAdd(TKey key, TValue value) => TryInsert(key, value, InsertionBehavior.None);
+
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }