DictionaryExtensionsTryAddTKey, TValue(IDictionaryTKey, TValue, TKey, 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.

Definition

Namespace: KGySoft.CoreLibraries
Assembly: KGySoft.CoreLibraries (in KGySoft.CoreLibraries.dll) Version: 10.5.0
C#
public static bool TryAdd<TKey, TValue>(
	IDictionary<TKey, TValue> dictionary,
	TKey key,
	TValue value
)

Parameters

dictionary  IDictionaryTKey, TValue
The target dictionary.
key  TKey
The key of the element to add.
value  TValue
The value of the element to add. The value can be for reference types.

Type Parameters

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

Return Value

Boolean
if the key and value pair was added to the dictionary successfully; if the key already exists or when IsReadOnly returns for the specified dictionary.

Remarks

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.

  Caution

To avoid ambiguity issues with System.Collections.Generic.CollectionExtensions.TryAdd, this method is declared as an extension method only in the .NET Framework and .NET Standard 2.0 builds. Whereas in .NET Core and .NET Standard 2.0 builds it is not an extension method. It means that using TryAdd as an extension may map to different implementations. To avoid that, call this method as a regular one, or use the TryAddTKey, TValue(IDictionaryTKey, TValue, KeyValuePairTKey, TValue) overload, which is a proper extension method on all platforms.

Exceptions

ArgumentNullExceptiondictionary is .

See Also