DictionaryExtensionsTryAddTKey, TValue Method

Tries to add a pair of key and value the specified dictionary. The operation is thread safe if dictionary is a ThreadSafeDictionaryTKey, TValue, ConcurrentDictionaryTKey, TValue or LockingDictionaryTKey, TValue instance. For other IDictionaryTKey, TValue implementations the caller should care about thread safety if needed.


Namespace: KGySoft.CoreLibraries
Assembly: KGySoft.CoreLibraries (in KGySoft.CoreLibraries.dll) Version: 7.0.0-rc.1
public static bool TryAdd<TKey, TValue>(
	this IDictionary<TKey, TValue> dictionary,
	KeyValuePair<TKey, TValue> item


dictionary  IDictionaryTKey, TValue
The target dictionary.
item  KeyValuePairTKey, TValue
The KeyValuePairTKey, TValue to add to the dictionary.

Type Parameters

The type of the keys in the dictionary.
The type of the values in the dictionary.

Return Value

if item was added to the dictionary successfully; if the key already exists or when IsReadOnly returns for dictionary.

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type IDictionaryTKey, TValue. When you use instance method syntax to call this method, omit the first parameter. For more information, see Extension Methods (Visual Basic) or Extension Methods (C# Programming Guide).


The CollectionExtensions class in .NET Core 2.0 and above also has a TryAdd method that behaves somewhat differently. To avoid ambiguity with that method this one has a KeyValuePairTKey, TValue parameter.

Unlike the CollectionExtensions.TryAdd method, this one is thread safe when used with ConcurrentDictionaryTKey, TValue, ThreadSafeDictionaryTKey, TValue and LockingDictionaryTKey, TValue instances. Additionally, this one returns if dictionary is read-only instead of throwing an exception.


ArgumentNullExceptiondictionary is .
ArgumentExceptionitem has a key.

See Also