EvictingDictionary<TKey, TValue> Class
Definition
Represents a fixed-capacity dictionary that automatically removes entries based on a chosen eviction policy, such as First-In-First-Out (FirstInFirstOut), Least Recently Used (LeastRecentlyUsed), or Least Frequently Used (LeastFrequentlyUsed).
public class EvictingDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable where TKey : notnull
Type Parameters
TKeySpecifies the type of keys in the dictionary.
TValueSpecifies the type of values in the dictionary.
- Inheritance
-
EvictingDictionary<TKey, TValue>
- Implements
-
IDictionary<TKey, TValue>ICollection<KeyValuePair<TKey, TValue>>IEnumerable<KeyValuePair<TKey, TValue>>
- Inherited Members
- Extension Methods
Remarks
EvictingDictionary<TKey, TValue> maintains a maximum number of key-value pairs and automatically evicts items when capacity is exceeded. Eviction is determined by a specified EvictingDictionaryPolicy, allowing this dictionary to behave like a queue, an access-order cache, or a frequency-based cache.
Keys must be non-null (the type parameter is constrained by notnull). Values may be
null when TValue is a reference type. Custom key equality is supported
via IEqualityComparer<T>.
Calling Add(TKey, TValue) (or assigning via the indexer) with a key
that already exists replaces the existing entry's value rather than throwing - this differs from
Dictionary<TKey, TValue>'s strict Add semantics. The replacement
counts as a touch against the eviction policy: recency-based policies move the entry to the most-recently-used
position, LeastFrequentlyUsed increments its accumulated frequency, and SecondChance marks it recently referenced.
The entry is not treated as newly inserted, and its accumulated metadata is not reset.
Supplying an EvictingDictionaryExpiration at construction adds time-based expiry orthogonal to the capacity policy: entries carry a time-to-live (a per-dictionary default and/or per-entry overrides), expired entries are invisible to lookups and enumeration even before they are physically removed, and removal happens lazily - when an access touches an expired key, when capacity pressure purges expired entries ahead of a policy eviction, or when RemoveExpired() is called explicitly. Note that Count reports the raw stored count including expired-but-unpurged entries; call RemoveExpired() to reconcile. Without an expiration configuration the dictionary performs no clock reads.
EvictingDictionary<TKey, TValue> is not thread-safe. Concurrent reads and writes (including reads, which mutate eviction metadata for some policies) require external synchronization.
// Create an evicting dictionary with capacity for 2 items using LRU eviction.
var cache = new EvictingDictionary<string, int>(capacity: 2, EvictingDictionaryPolicy.LeastRecentlyUsed);
// Add two entries.
cache["A"] = 1;
cache["B"] = 2;
// Touch "A" to mark it as recently used.
cache.Touch("A");
// Add a third entry; "B" is now the least recently used and will be evicted.
cache["C"] = 3;
// Dictionary now contains: { "A": 1, "C": 3 }
foreach (var kvp in cache)
Console.WriteLine($"{kvp.Key} = {kvp.Value}");
// Output:
// A = 1
// C = 3
Constructors
EvictingDictionary()
Initializes a new instance of the EvictingDictionary<TKey, TValue> class, with the default capacity and eviction policy.
public EvictingDictionary()
Remarks
Creates an empty dictionary with a capacity of Bodu.Collections.Generic.EvictingDictionary`2.DefaultCapacity items, using Bodu.Collections.Generic.EvictingDictionary`2.DefaultPolicy for eviction when capacity is exceeded, and the default key comparer ( Default).
EvictingDictionary(IEnumerable<KeyValuePair<TKey, TValue>>)
Initializes a new instance of the EvictingDictionary<TKey, TValue> class, with elements copied from the specified sequence, using the default capacity and eviction policy.
public EvictingDictionary(IEnumerable<KeyValuePair<TKey, TValue>> source)
Parameters
sourceIEnumerable<KeyValuePair<TKey, TValue>>The sequence of key/value pairs to copy. Must not be null.
Remarks
Creates a dictionary containing the elements from source.
Uses a capacity of Bodu.Collections.Generic.EvictingDictionary`2.DefaultCapacity, Bodu.Collections.Generic.EvictingDictionary`2.DefaultPolicy for eviction, and the default key comparer. If more elements are provided than the capacity allows, entries are evicted according to the policy.
Exceptions
- ArgumentNullException
sourceis null.
EvictingDictionary(IEnumerable<KeyValuePair<TKey, TValue>>, EvictingDictionaryPolicy)
Initializes a new instance of the EvictingDictionary<TKey, TValue> class, with elements copied from the specified sequence, using the default capacity and the specified eviction policy.
public EvictingDictionary(IEnumerable<KeyValuePair<TKey, TValue>> source, EvictingDictionaryPolicy policy)
Parameters
sourceIEnumerable<KeyValuePair<TKey, TValue>>The sequence of key/value pairs to copy. Must not be null.
policyEvictingDictionaryPolicyThe eviction policy used when capacity is exceeded.
Remarks
Uses a capacity of Bodu.Collections.Generic.EvictingDictionary`2.DefaultCapacity, the specified eviction policy, and the default key comparer. If more elements are provided than the capacity allows, entries are evicted according to the policy.
Exceptions
- ArgumentNullException
sourceis null.
EvictingDictionary(int)
Initializes a new instance of the EvictingDictionary<TKey, TValue> class, with the specified capacity and the default eviction policy.
public EvictingDictionary(int capacity)
Parameters
capacityintThe maximum number of key/value pairs the dictionary can contain. Must be positive.
Remarks
Creates an empty dictionary with the specified capacity, using Bodu.Collections.Generic.EvictingDictionary`2.DefaultPolicy for eviction when capacity is exceeded, and the default key comparer ( Default).
Exceptions
- ArgumentOutOfRangeException
capacityis less than or equal to zero.
EvictingDictionary(int, EvictingDictionaryExpiration?)
Initializes a new instance of the EvictingDictionary<TKey, TValue> class, with the specified capacity and time-based expiration, using the default eviction policy and key comparer.
public EvictingDictionary(int capacity, EvictingDictionaryExpiration? expiration)
Parameters
capacityintThe maximum number of key/value pairs the dictionary can contain. Must be positive.
expirationEvictingDictionaryExpirationThe time-based expiration configuration, or null to disable expiry.
Remarks
Creates an empty dictionary with the specified capacity and expiration configuration, using Bodu.Collections.Generic.EvictingDictionary`2.DefaultPolicy for eviction when capacity is exceeded and the default key comparer.
Exceptions
- ArgumentOutOfRangeException
capacityis less than or equal to zero.
EvictingDictionary(int, EvictingDictionaryPolicy)
Initializes a new instance of the EvictingDictionary<TKey, TValue> class, with the specified capacity and eviction policy.
public EvictingDictionary(int capacity, EvictingDictionaryPolicy policy)
Parameters
capacityintThe maximum number of key/value pairs the dictionary can contain. Must be positive.
policyEvictingDictionaryPolicyThe eviction policy used when capacity is exceeded.
Remarks
Creates an empty dictionary with the specified capacity, using the specified eviction policy, and the default key comparer ( Default).
Exceptions
- ArgumentOutOfRangeException
capacityis less than or equal to zero.
EvictingDictionary(int, EvictingDictionaryPolicy, EvictingDictionaryExpiration?)
Initializes a new instance of the EvictingDictionary<TKey, TValue> class, with the specified capacity, eviction policy, and time-based expiration, using the default key comparer.
public EvictingDictionary(int capacity, EvictingDictionaryPolicy policy, EvictingDictionaryExpiration? expiration)
Parameters
capacityintThe maximum number of key/value pairs the dictionary can contain. Must be positive.
policyEvictingDictionaryPolicyThe eviction policy used when capacity is exceeded.
expirationEvictingDictionaryExpirationThe time-based expiration configuration, or null to disable expiry.
Remarks
Creates an empty dictionary with the specified capacity, eviction policy, and expiration configuration, using the default key comparer ( Default).
Exceptions
- ArgumentOutOfRangeException
capacityis less than or equal to zero.
EvictingDictionary(int, EvictingDictionaryPolicy, IEqualityComparer<TKey>?)
Initializes a new instance of the EvictingDictionary<TKey, TValue> class, with the specified capacity, eviction policy, and key comparer.
public EvictingDictionary(int capacity, EvictingDictionaryPolicy policy, IEqualityComparer<TKey>? comparer)
Parameters
capacityintThe maximum number of key/value pairs the dictionary can contain. Must be positive.
policyEvictingDictionaryPolicyThe eviction policy used when capacity is exceeded.
comparerIEqualityComparer<TKey>The equality comparer to use for keys, or null to use the default comparer.
Remarks
Creates an empty dictionary with the specified capacity and eviction policy, using the specified key comparer.
Initializes the internal storage for key/value pairs, and, where applicable, the eviction tracking structure: FIFO, LRU, MRU, and SecondChance use a linked list; LFU uses a sorted dictionary of frequency lists; RandomReplacement does not require additional tracking.
Exceptions
- ArgumentOutOfRangeException
capacityis less than or equal to zero.
EvictingDictionary(int, EvictingDictionaryPolicy, IEqualityComparer<TKey>?, EvictingDictionaryExpiration?)
Initializes a new instance of the EvictingDictionary<TKey, TValue> class, with the specified capacity, eviction policy, key comparer, and time-based expiration.
public EvictingDictionary(int capacity, EvictingDictionaryPolicy policy, IEqualityComparer<TKey>? comparer, EvictingDictionaryExpiration? expiration)
Parameters
capacityintThe maximum number of key/value pairs the dictionary can contain. Must be positive.
policyEvictingDictionaryPolicyThe eviction policy used when capacity is exceeded.
comparerIEqualityComparer<TKey>The equality comparer to use for keys, or null to use the default comparer.
expirationEvictingDictionaryExpirationThe time-based expiration configuration, or null to disable expiry.
Remarks
Creates an empty dictionary with the specified capacity, eviction policy, key comparer, and expiration configuration.
Initializes the internal storage for key/value pairs, and, where applicable, the eviction tracking structure:
FIFO, LRU, MRU, and SecondChance use a linked list; LFU uses a sorted dictionary of frequency lists;
RandomReplacement does not require additional tracking. When expiration is
null the dictionary performs no clock reads and behaves as a capacity-only cache.
Exceptions
- ArgumentOutOfRangeException
capacityis less than or equal to zero.
EvictingDictionary(int, IEnumerable<KeyValuePair<TKey, TValue>>)
Initializes a new instance of the EvictingDictionary<TKey, TValue> class, with elements copied from the specified sequence, using the specified capacity and the default eviction policy.
public EvictingDictionary(int capacity, IEnumerable<KeyValuePair<TKey, TValue>> source)
Parameters
capacityintThe maximum number of key/value pairs the dictionary can contain. Must be positive.
sourceIEnumerable<KeyValuePair<TKey, TValue>>The sequence of key/value pairs to copy. Must not be null.
Remarks
Creates a dictionary containing the elements from source.
Uses the specified capacity, Bodu.Collections.Generic.EvictingDictionary`2.DefaultPolicy for eviction, and the default key comparer. If more elements are provided than the capacity allows, entries are evicted according to the policy.
Exceptions
- ArgumentNullException
sourceis null.- ArgumentOutOfRangeException
capacityis less than or equal to zero.
EvictingDictionary(int, IEnumerable<KeyValuePair<TKey, TValue>>, EvictingDictionaryPolicy)
Initializes a new instance of the EvictingDictionary<TKey, TValue> class, with elements copied from the specified sequence, using the specified capacity and eviction policy.
public EvictingDictionary(int capacity, IEnumerable<KeyValuePair<TKey, TValue>> source, EvictingDictionaryPolicy policy)
Parameters
capacityintThe maximum number of key/value pairs the dictionary can contain. Must be positive.
sourceIEnumerable<KeyValuePair<TKey, TValue>>The sequence of key/value pairs to copy. Must not be null.
policyEvictingDictionaryPolicyThe eviction policy used when capacity is exceeded.
Remarks
Uses the specified capacity, the specified eviction policy, and the default key comparer. If more elements are provided than the capacity allows, entries are evicted according to the policy.
Exceptions
- ArgumentNullException
sourceis null.- ArgumentOutOfRangeException
capacityis less than or equal to zero.
EvictingDictionary(int, IEnumerable<KeyValuePair<TKey, TValue>>, EvictingDictionaryPolicy, IEqualityComparer<TKey>?)
Initializes a new instance of the EvictingDictionary<TKey, TValue> class, with elements copied from the specified sequence, using the specified capacity, eviction policy, and key comparer.
public EvictingDictionary(int capacity, IEnumerable<KeyValuePair<TKey, TValue>> source, EvictingDictionaryPolicy policy, IEqualityComparer<TKey>? comparer)
Parameters
capacityintThe maximum number of key/value pairs the dictionary can contain. Must be positive.
sourceIEnumerable<KeyValuePair<TKey, TValue>>The sequence of key/value pairs to copy. Must not be null.
policyEvictingDictionaryPolicyThe eviction policy used when capacity is exceeded.
comparerIEqualityComparer<TKey>The equality comparer to use for keys, or null to use the default comparer.
Remarks
Uses the specified capacity, the specified eviction policy, and the specified key comparer (or
Default if comparer is null). If
more elements are provided than the capacity allows, entries are evicted according to the policy.
Exceptions
- ArgumentNullException
sourceis null.- ArgumentOutOfRangeException
capacityis less than or equal to zero.
EvictingDictionary(int, IEnumerable<KeyValuePair<TKey, TValue>>, EvictingDictionaryPolicy, IEqualityComparer<TKey>?, EvictingDictionaryExpiration?)
Initializes a new instance of the EvictingDictionary<TKey, TValue> class, with elements copied from the specified sequence, using the specified capacity, eviction policy, key comparer, and time-based expiration.
public EvictingDictionary(int capacity, IEnumerable<KeyValuePair<TKey, TValue>> source, EvictingDictionaryPolicy policy, IEqualityComparer<TKey>? comparer, EvictingDictionaryExpiration? expiration)
Parameters
capacityintThe maximum number of key/value pairs the dictionary can contain. Must be positive.
sourceIEnumerable<KeyValuePair<TKey, TValue>>The sequence of key/value pairs to copy. Must not be null.
policyEvictingDictionaryPolicyThe eviction policy used when capacity is exceeded.
comparerIEqualityComparer<TKey>The equality comparer to use for keys, or null to use the default comparer.
expirationEvictingDictionaryExpirationThe time-based expiration configuration, or null to disable expiry.
Remarks
Uses the specified capacity, eviction policy, key comparer, and expiration configuration. Copied entries receive the default TimeToLive (when configured); if more elements are provided than the capacity allows, entries are evicted according to the policy.
Exceptions
- ArgumentNullException
sourceis null.- ArgumentOutOfRangeException
capacityis less than or equal to zero.
EvictingDictionary(int, IEqualityComparer<TKey>?)
Initializes a new instance of the EvictingDictionary<TKey, TValue> class, with the specified capacity, using the default eviction policy and the specified key comparer.
public EvictingDictionary(int capacity, IEqualityComparer<TKey>? comparer)
Parameters
capacityintThe maximum number of key/value pairs the dictionary can contain. Must be positive.
comparerIEqualityComparer<TKey>The equality comparer to use for keys, or null to use the default comparer.
Remarks
Creates an empty dictionary with the specified capacity, using Bodu.Collections.Generic.EvictingDictionary`2.DefaultPolicy for eviction when
capacity is exceeded, and the specified key comparer (or Default if
comparer is null).
Exceptions
- ArgumentOutOfRangeException
capacityis less than or equal to zero.
Properties
Capacity
Gets the maximum number of items that can be stored in the dictionary before eviction occurs.
public int Capacity { get; }
Property Value
Count
Gets the number of key/value pairs physically stored in the dictionary.
public int Count { get; }
Property Value
- int
The raw stored count, including expired entries that have not yet been purged.
Remarks
When time-based expiration is configured, this property deliberately reports the raw stored count - including expired-but-unpurged entries - so it remains an O(1) read that never touches the clock. Expired entries are invisible to ContainsKey(TKey), TryGetValue(TKey, out TValue), the indexer getter, and enumeration, so Count may exceed the number of entries those members observe.
Call RemoveExpired() to purge expired entries and reconcile Count with the live set. Without an expiration configuration the raw count and the live count are always identical.
EvictionCount
Gets the total number of items evicted from the dictionary since creation.
public long EvictionCount { get; }
Property Value
Expiration
Gets the time-based expiration configuration for this dictionary, or null when expiration is disabled.
public EvictingDictionaryExpiration? Expiration { get; }
Property Value
- EvictingDictionaryExpiration
The EvictingDictionaryExpiration supplied at construction, or null when the dictionary was constructed without one. When null the dictionary performs no clock reads and behaves as a capacity-only cache.
IsReadOnly
Gets a value indicating whether the ICollection<T> is read-only.
public bool IsReadOnly { get; }
Property Value
- bool
true if the ICollection<T> is read-only; otherwise, false.
this[TKey]
Gets or sets the element with the specified key.
public TValue this[TKey key] { get; set; }
Parameters
keyTKeyThe key of the element to get or set.
Property Value
- TValue
The element with the specified key.
Exceptions
- ArgumentNullException
keyis null.- KeyNotFoundException
The property is retrieved and
keyis not found.- NotSupportedException
The property is set and the IDictionary<TKey, TValue> is read-only.
Keys
Gets an ICollection<T> containing the keys of the IDictionary<TKey, TValue>.
public ICollection<TKey> Keys { get; }
Property Value
- ICollection<TKey>
An ICollection<T> containing the keys of the object that implements IDictionary<TKey, TValue>.
Remarks
Returns a live, order-preserving view of the dictionary's keys. The collection is cached per instance, so repeated reads of Keys do not allocate; enumeration is in the order defined by the current EvictingDictionaryPolicy.
Policy
Gets the eviction policy configured for this dictionary.
public EvictingDictionaryPolicy Policy { get; }
Property Value
TotalTouches
Gets the total number of times any key has been accessed or touched.
public long TotalTouches { get; }
Property Value
Values
Gets an ICollection<T> containing the values in the IDictionary<TKey, TValue>.
public ICollection<TValue> Values { get; }
Property Value
- ICollection<TValue>
An ICollection<T> containing the values in the object that implements IDictionary<TKey, TValue>.
Remarks
Returns a live, order-preserving view of the dictionary's values. The collection is cached per instance, so repeated reads of Values do not allocate; enumeration is in the order defined by the current EvictingDictionaryPolicy.
Methods
Add(KeyValuePair<TKey, TValue>)
Adds the specified key/value pair to the dictionary. If the dictionary has reached its capacity, an existing entry will be evicted according to the configured EvictingDictionaryPolicy.
public void Add(KeyValuePair<TKey, TValue> item)
Parameters
itemKeyValuePair<TKey, TValue>The key/value pair to add to the dictionary.
Exceptions
- ArgumentNullException
item.Keyis null.
Add(TKey, TValue)
Adds the specified key and value to the dictionary, or replaces the value if the key already exists. If the dictionary has reached its capacity and the key is new, an existing entry will be evicted according to the configured EvictingDictionaryPolicy.
public void Add(TKey key, TValue value)
Parameters
keyTKeyThe key of the element to add or update.
valueTValueThe value to associate with
key.
Remarks
When an entry for key already exists its value is updated in place and the write counts as a
touch against the eviction policy: recency-based policies move the entry to the most-recently-used position,
LeastFrequentlyUsed increments its accumulated frequency, and SecondChance marks it recently referenced. The
entry keeps its accumulated metadata rather than being treated as newly inserted. This differs from
Add(TKey, TValue), which throws on duplicate
keys.
When time-based expiration is configured, each write is a fresh lease: the entry's lifetime restarts using the dictionary default TimeToLive (any per-entry override from a previous Add(TKey, TValue, TimeSpan) is discarded). If the existing entry has expired it is lazily removed first and the new entry is added with fresh eviction metadata. On capacity pressure, expired entries are purged before the policy selects a victim.
Exceptions
- ArgumentNullException
keyis null.- InvalidOperationException
Thrown if invoked from within an ItemEvicting or ItemEvicted event handler.
Add(TKey, TValue, TimeSpan)
Adds the specified key and value to the dictionary with an explicit time-to-live, or replaces the value and restarts the lifetime if the key already exists. If the dictionary has reached its capacity and the key is new, expired entries are purged first and, when none exist, an entry is evicted according to the configured EvictingDictionaryPolicy.
public void Add(TKey key, TValue value, TimeSpan timeToLive)
Parameters
keyTKeyThe key of the element to add or update.
valueTValueThe value to associate with
key.timeToLiveTimeSpanThe lifetime for this entry, overriding the dictionary's default TimeToLive.
Remarks
The per-entry timeToLive applies to this write only: a later update through
Add(TKey, TValue) or the indexer setter discards the override and re-applies the dictionary
default. Under Sliding, successful read accesses refresh the
deadline using this entry's own time-to-live.
If an entry for key exists but has expired, it is lazily removed (raising the eviction
events) and the new entry is added with fresh eviction metadata.
Exceptions
- ArgumentNullException
keyis null.- ArgumentOutOfRangeException
timeToLiveis less than or equal to Zero.- InvalidOperationException
No Expiration configuration was supplied at construction, or the method is invoked from within an ItemEvicting or ItemEvicted event handler.
Clear()
Removes all entries from the dictionary and resets internal tracking counters.
public void Clear()
Remarks
Clears the dictionary and resets all internal eviction metadata, including access order (for LeastRecentlyUsed and MostRecentlyUsed), frequency tracking (for LeastFrequentlyUsed), and counters such as TotalTouches and EvictionCount.
Exceptions
- InvalidOperationException
Thrown if invoked from within an ItemEvicting or ItemEvicted event handler.
Contains(KeyValuePair<TKey, TValue>)
Determines whether the ICollection<T> contains a specific value.
public bool Contains(KeyValuePair<TKey, TValue> item)
Parameters
itemKeyValuePair<TKey, TValue>The object to locate in the ICollection<T>.
Returns
- bool
true if
itemis found in the ICollection<T>; otherwise, false.
Remarks
Like ContainsKey(TKey), this is a pure read with respect to the capacity policy: it does not update recency or frequency metadata, slide expiration, or count as a touch. (Reads that should influence eviction order go through TryGetValue(TKey, out TValue) or the indexer.)
ContainsKey(TKey)
Determines whether the IDictionary<TKey, TValue> contains an element with the specified key.
public bool ContainsKey(TKey key)
Parameters
keyTKeyThe key to locate in the IDictionary<TKey, TValue>.
Returns
- bool
true if the IDictionary<TKey, TValue> contains an element with the key; otherwise, false.
Remarks
This is a pure read: it does not update recency or frequency metadata, count as a touch, or slide the expiration deadline. When time-based expiration is configured, an expired entry still counts as absent - it is lazily removed and false is returned - but a live hit leaves the entry's sliding deadline unchanged. Use TryGetValue(TKey, out TValue) or the indexer getter for a read that slides the deadline under Sliding.
Exceptions
- ArgumentNullException
keyis null.
CopyTo(KeyValuePair<TKey, TValue>[], int)
Copies the elements of the ICollection<T> to an Array, starting at a particular Array index.
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
Parameters
arrayKeyValuePair<TKey, TValue>[]The one-dimensional Array that is the destination of the elements copied from ICollection<T>. The Array must have zero-based indexing.
arrayIndexintThe zero-based index in
arrayat which copying begins.
Remarks
When time-based expiration is configured, expired entries are purged (raising the eviction events) before the
copy, so Count read after the call matches the number of elements written. Callers that
size a destination from Count before invoking this method (as LINQ's ToArray does) should
call RemoveExpired() first to avoid trailing default slots.
Exceptions
- ArgumentNullException
arrayis null.- ArgumentOutOfRangeException
arrayIndexis less than 0.- ArgumentException
The number of elements in the source ICollection<T> is greater than the available space from
arrayIndexto the end of the destinationarray.
GetEnumerator()
Returns an enumerator that iterates through the dictionary in the order defined by the current EvictingDictionaryPolicy.
public EvictingDictionary<TKey, TValue>.Enumerator GetEnumerator()
Returns
- EvictingDictionary<TKey, TValue>.Enumerator
An EvictingDictionary<TKey, TValue>.Enumerator over the dictionary's live entries.
Remarks
When time-based expiration is configured, the clock is read once when the enumerator is created and expired entries are filtered out (never removed) against that snapshot, so a single enumeration observes a stable set and never refreshes sliding deadlines.
PeekEvictionCandidate()
Returns the key that would be evicted next based on the current eviction policy and internal state.
public TKey? PeekEvictionCandidate()
Returns
- TKey
The key that is next in line for eviction, or default if the dictionary is empty.
Remarks
The eviction candidate depends on the selected EvictingDictionaryPolicy:
- FirstInFirstOut: returns the oldest inserted key.
- LeastRecentlyUsed: returns the least recently accessed key.
- MostRecentlyUsed: returns the most recently accessed key.
- LeastFrequentlyUsed: returns the key with the fewest total accesses.
- RandomReplacement: returns an arbitrary key from the dictionary.
- SecondChance: returns the first key that has not been accessed recently; falls back to FIFO if all have second chances.
This is a pure read that never touches the clock: when time-based expiration is configured it may return an expired-but-unpurged key, even though capacity pressure purges expired entries before consulting the policy.
Remove(KeyValuePair<TKey, TValue>)
Removes the first occurrence of a specific object from the ICollection<T>.
public bool Remove(KeyValuePair<TKey, TValue> item)
Parameters
itemKeyValuePair<TKey, TValue>The object to remove from the ICollection<T>.
Returns
- bool
true if
itemwas successfully removed from the ICollection<T>; otherwise, false. This method also returns false ifitemis not found in the original ICollection<T>.
Exceptions
- NotSupportedException
The ICollection<T> is read-only.
Remove(TKey)
Removes the element with the specified key from the IDictionary<TKey, TValue>.
public bool Remove(TKey key)
Parameters
keyTKeyThe key of the element to remove.
Returns
- bool
true if the element is successfully removed; otherwise, false. This method also returns false if
keywas not found in the original IDictionary<TKey, TValue>.
Remarks
Remove(TKey) operates on physically stored entries: when time-based expiration is configured it also removes an expired-but-unpurged entry and returns true, without raising the eviction events (consistent with Count reporting the raw stored count).
Exceptions
- ArgumentNullException
keyis null.- NotSupportedException
The IDictionary<TKey, TValue> is read-only.
- InvalidOperationException
Thrown if invoked from within an ItemEvicting or ItemEvicted event handler.
RemoveExpired()
Removes every expired entry from the dictionary and returns the number of entries removed.
public int RemoveExpired()
Returns
- int
The number of expired entries that were removed;
0when nothing had expired or when no Expiration configuration was supplied at construction.
Remarks
Each removal raises the ItemEvicting and ItemEvicted events and increments EvictionCount, exactly as a capacity-triggered eviction does.
The dictionary never removes expired entries on a background timer; besides the lazy removal performed when an access touches an expired key, this method is the way to reconcile Count with the set of live entries. Call it periodically for caches that can sit idle for long periods.
Exceptions
- InvalidOperationException
Thrown if invoked from within an ItemEvicting or ItemEvicted event handler.
Touch(TKey)
Marks the specified key as recently accessed without retrieving its value. If the eviction policy involves usage tracking, this updates the internal usage metadata.
public bool Touch(TKey key)
Parameters
keyTKeyThe key to touch.
Returns
Remarks
When time-based expiration is configured, an expired entry counts as absent: it is lazily removed (raising the eviction events) and false is returned. Touch(TKey) affects only the capacity-policy metadata - it does not refresh a sliding expiration deadline; use a read access ( TryGetValue(TKey, out TValue) or the indexer getter) to slide. Like ContainsKey(TKey), it is a pure read with respect to the deadline.
TouchOrThrow(TKey)
Marks the specified key as recently accessed without retrieving its value, and throws an exception if the key does not exist in the dictionary.
public void TouchOrThrow(TKey key)
Parameters
keyTKeyThe key to touch.
Remarks
If the eviction policy is LeastRecentlyUsed or LeastFrequentlyUsed, this updates the internal usage metadata.
Exceptions
- KeyNotFoundException
The specified
keydoes not exist in the dictionary.
TryAdd(TKey, TValue, TimeSpan)
Attempts to add the specified key and value to the dictionary with an explicit time-to-live, without replacing an existing live entry.
public bool TryAdd(TKey key, TValue value, TimeSpan timeToLive)
Parameters
keyTKeyThe key of the element to add.
valueTValueThe value to associate with
key.timeToLiveTimeSpanThe lifetime for this entry, overriding the dictionary's default TimeToLive.
Returns
Remarks
An expired-but-unpurged entry for key does not block the add: it is lazily removed (raising
the eviction events) and the new entry is added, returning true. If the dictionary is at
capacity, expired entries are purged first and, when none exist, an entry is evicted according to the configured
EvictingDictionaryPolicy.
Exceptions
- ArgumentNullException
keyis null.- ArgumentOutOfRangeException
timeToLiveis less than or equal to Zero.- InvalidOperationException
No Expiration configuration was supplied at construction, or the method is invoked from within an ItemEvicting or ItemEvicted event handler.
TryGetValue(TKey, out TValue)
Attempts to retrieve the value associated with the specified key.
public bool TryGetValue(TKey key, out TValue value)
Parameters
keyTKeyThe key of the value to retrieve.
valueTValueWhen this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter.
Returns
Remarks
A successful read counts as an access for the configured EvictingDictionaryPolicy: recency-tracked policies ( LeastRecentlyUsed and MostRecentlyUsed) reposition the key, LeastFrequentlyUsed increments its frequency, and SecondChance sets its reference flag. FirstInFirstOut and RandomReplacement are unaffected by reads.
TotalTouches is incremented on every successful lookup regardless of policy.
When time-based expiration is configured, an expired entry counts as absent: it is lazily removed (raising the eviction events) and false is returned. A hit refreshes the entry's deadline under Sliding.
Events
ItemEvicted
Occurs immediately after an item is evicted from the EvictingDictionary<TKey, TValue> due to capacity limits.
public event Action<TKey, TValue>? ItemEvicted
Event Type
- Action<TKey, TValue>
Examples
var cache = new EvictingDictionary<string, int>(capacity: 2, EvictingDictionaryPolicy.FirstInFirstOut);
cache.ItemEvicted += (key, value) =>
{
Console.WriteLine($"[AfterEvict] {key} = {value}");
};
cache.Add("A", 1);
cache.Add("B", 2);
cache.Add("C", 3); // Triggers ItemEvicted for "A".
Remarks
This event is raised after the item has been removed from the collection, based on the configured EvictingDictionaryPolicy (e.g., FirstInFirstOut, LeastRecentlyUsed, or LeastFrequentlyUsed).
Consumers can use this event to record historical data, notify observers, or synchronize external caches. The key and value provided are no longer present in the dictionary.
ItemEvicting
Occurs immediately before an item is evicted from the EvictingDictionary<TKey, TValue> due to capacity limits.
public event Action<TKey, TValue>? ItemEvicting
Event Type
- Action<TKey, TValue>
Examples
var cache = new EvictingDictionary<string, int>(capacity: 2, EvictingDictionaryPolicy.FirstInFirstOut);
cache.ItemEvicting += (key, value) =>
{
Console.WriteLine($"[BeforeEvict] {key} = {value}");
};
cache.Add("A", 1);
cache.Add("B", 2);
cache.Add("C", 3); // Triggers ItemEvicting for "A".
Remarks
This event is raised before the item is removed from the collection, allowing consumers to inspect the key and value before eviction occurs.
Common use cases include diagnostics, logging, cache warm-up, or state mirroring. This event is informational and cannot cancel or delay eviction.
Explicit Interface Implementations
IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
Returns an enumerator that iterates through the collection.
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
Returns
- IEnumerator<KeyValuePair<TKey, TValue>>
An enumerator that can be used to iterate through the collection.
ICollection.CopyTo(Array, int)
Copies the elements of the ICollection to an Array, starting at a particular Array index.
void ICollection.CopyTo(Array array, int index)
Parameters
arrayArrayThe one-dimensional Array that is the destination of the elements copied from ICollection. The Array must have zero-based indexing.
indexintThe zero-based index in
arrayat which copying begins.
Exceptions
- ArgumentNullException
arrayis null.- ArgumentOutOfRangeException
indexis less than zero.- ArgumentException
arrayis multidimensional.-or-
The number of elements in the source ICollection is greater than the available space from
indexto the end of the destinationarray.-or-
The type of the source ICollection cannot be cast automatically to the type of the destination
array.
ICollection.IsSynchronized
Gets a value indicating whether access to the ICollection is synchronized (thread safe).
bool ICollection.IsSynchronized { get; }
Returns
- bool
true if access to the ICollection is synchronized (thread safe); otherwise, false.
ICollection.SyncRoot
Gets an object that can be used to synchronize access to the ICollection.
object ICollection.SyncRoot { get; }
Returns
- object
An object that can be used to synchronize access to the ICollection.
IDictionary.Add(object, object)
Adds an element with the provided key and value to the IDictionary object.
void IDictionary.Add(object key, object value)
Parameters
keyobjectThe object to use as the key of the element to add.
valueobjectThe object to use as the value of the element to add.
Exceptions
- ArgumentNullException
keyis null.- ArgumentException
An element with the same key already exists in the IDictionary object.
- NotSupportedException
The IDictionary is read-only.
-or-
The IDictionary has a fixed size.
IDictionary.Contains(object)
Determines whether the IDictionary object contains an element with the specified key.
bool IDictionary.Contains(object key)
Parameters
keyobjectThe key to locate in the IDictionary object.
Returns
- bool
true if the IDictionary contains an element with the key; otherwise, false.
Exceptions
- ArgumentNullException
keyis null.
IDictionary.GetEnumerator()
Returns an IDictionaryEnumerator object for the IDictionary object.
IDictionaryEnumerator IDictionary.GetEnumerator()
Returns
- IDictionaryEnumerator
An IDictionaryEnumerator object for the IDictionary object.
IDictionary.IsFixedSize
Gets a value indicating whether the IDictionary object has a fixed size.
bool IDictionary.IsFixedSize { get; }
Returns
- bool
true if the IDictionary object has a fixed size; otherwise, false.
IDictionary.IsReadOnly
Gets a value indicating whether the IDictionary object is read-only.
bool IDictionary.IsReadOnly { get; }
Returns
- bool
true if the IDictionary object is read-only; otherwise, false.
IDictionary.Item[object]
Gets or sets the element with the specified key.
object? IDictionary.Item[object key] { get; set; }
Parameters
keyobjectThe key of the element to get or set.
Returns
Remarks
Following the Dictionary<TKey, TValue> contract for this[object], the getter throws ArgumentNullException for a null key and returns null for a non-null key of an incompatible type.
Exceptions
- ArgumentNullException
keyis null.- NotSupportedException
The property is set and the IDictionary object is read-only.
-or-
The property is set,
keydoes not exist in the collection, and the IDictionary has a fixed size.
IDictionary.Keys
Gets an ICollection object containing the keys of the IDictionary object.
ICollection IDictionary.Keys { get; }
Returns
- ICollection
An ICollection object containing the keys of the IDictionary object.
IDictionary.Remove(object)
Removes the element with the specified key from the IDictionary object.
void IDictionary.Remove(object key)
Parameters
keyobjectThe key of the element to remove.
Exceptions
- ArgumentNullException
keyis null.- NotSupportedException
The IDictionary object is read-only.
-or-
The IDictionary has a fixed size.
IDictionary.Values
Gets an ICollection object containing the values in the IDictionary object.
ICollection IDictionary.Values { get; }
Returns
- ICollection
An ICollection object containing the values in the IDictionary object.
IDictionary.get_Item(object)
object IDictionary.get_Item(object key)
Parameters
keyobject
Returns
IDictionary.set_Item(object, object)
void IDictionary.set_Item(object key, object value)
Parameters
IEnumerable.GetEnumerator()
Returns an enumerator that iterates through a collection.
IEnumerator IEnumerable.GetEnumerator()
Returns
- IEnumerator
An IEnumerator object that can be used to iterate through the collection.
Applies to
| Product | Versions |
|---|---|
| .NET | 8, 10 |