DictionaryExtensionsGetOrAddTKey, TValue, TArg(IDictionaryTKey, TValue, TKey, FuncTKey, TArg, TValue, TArg) Method

Adds a key/value pair to the dictionary by using the specified addValueFactory if the key does not already exist, and returns either the added or the existing value. 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 TValue GetOrAdd<TKey, TValue, TArg>(
	this IDictionary<TKey, TValue> dictionary,
	TKey key,
	Func<TKey, TArg, TValue> addValueFactory,
	TArg factoryArgument


dictionary  IDictionaryTKey, TValue
The target dictionary.
key  TKey
The key of the element to add or whose value should be returned.
addValueFactory  FuncTKey, TArg, TValue
The delegate to be used to generate the value, if the key does not already exist.
factoryArgument  TArg
An argument to pass into addValueFactory.

Type Parameters

The type of the keys in the dictionary.
The type of the values in the dictionary.
The type of an argument to pass into addValueFactory.

Return Value

The value for the key. This will be either the existing value for the key if the key is already in the dictionary, or the result of the specified addValueFactory if the key was not in the 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).


ArgumentNullExceptiondictionary, key or addValueFactory is .
NotSupportedExceptionkey was not present in the dictionary, which is read-only.

See Also