MemoryCache.AddOrGetExisting Method (String, Object, CacheItemPolicy, String)

.NET Framework (current version)

The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

Inserts a cache entry into the cache using the specified key and value and the specified details for how it is to be evicted.

Namespace:   System.Runtime.Caching
Assembly:  System.Runtime.Caching (in System.Runtime.Caching.dll)

public override object AddOrGetExisting(
	string key,
	object value,
	CacheItemPolicy policy,
	string regionName = null


Type: System.String

A unique identifier for the cache entry to add or get.

Type: System.Object

The data for the cache entry.

Type: System.Runtime.Caching.CacheItemPolicy

An object that contains eviction details for the cache entry. This object provides more options for eviction than a simple absolute expiration.

Type: System.String

A named region in the cache to which a cache entry can be added. Do not pass a value for this parameter. By default, this parameter is null, because the MemoryCache class does not implement regions.

Return Value

Type: System.Object

If a matching cache entry already exists, a cache entry; otherwise, null.

Exception Condition

key is null.


value is null.


Both the absolute and sliding expiration values of CacheItemPolicy object are set to values other than the defaults of InfiniteAbsoluteExpiration and NoSlidingExpiration. The MemoryCache class cannot set expiration policy based on a combination of both an absolute and a sliding expiration. Only one expiration setting can be explicitly set when you use the MemoryCache class. The other setting must be set to InfiniteAbsoluteExpiration or NoSlidingExpiration.


Both the removal callback and the update callback have been specified for CacheItemPolicy. The MemoryCache only supports using one type of callback per cache entry.


The SlidingExpiration property is set to a value less than Zero.


The SlidingExpiration has been set to a value greater than one year.


The Priority property is not a value of the CacheItemPriority enumeration.


The Add and AddOrGetExisting method overloads do not support the UpdateCallback property. Therefore, to set the UpdateCallback property for a cache entry, use the Set method overloads instead.

.NET Framework
Available since 4.0
Return to top