Set Method (String, Object, CacheItemPolicy, String)

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

.NET Framework (current version)

Inserts a cache entry into the cache by using a key and a value and eviction.

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

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


Type: System.String

A unique identifier for the cache entry to insert.

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. This parameter is null by default, because the MemoryCache class does not implement regions.

Exception Condition

key is null.


value is null


The callback reference that was passed to the helper method in the UpdateCallback property is null.

  • An invalid combination of arguments for the cache entry exists. This occurs if the following expiration details are set on the policy object for the cache entry:

  • If both the absolute and sliding expiration values on CacheItemPolicy object are set to values other than the defaults of InfiniteAbsoluteExpiration and NoSlidingExpiration. This is because the MemoryCache class does not support expiring entries based on 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.

  • If both the removal callback and the update callback are specified on CacheItemPolicy class. The MemoryCache class only supports using one type of callback per cache entry.


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


The SlidingExpiration property is set to a value greater than one year.


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


regionName is not null.

Like other Set method overloads, the Set method always puts a cache value in the cache, regardless whether a matching entry already exists. If the specified entry does not exist in the cache, a new cache entry is inserted. If the specified entry exists, it is updated.

Removing an entry triggers any associated change monitors. If the removed item was associated with a CacheItemUpdateCallback object or CacheItemRemovedCallback object, the reason for removal that is passed to the callbacks is contained in the Removed property.

.NET Framework
Available since 4.0
Return to top
© 2016 Microsoft