Skip to content

Alternate Lookups

Alex Peck edited this page May 12, 2026 · 2 revisions

Starting with v2.6.0 and .NET 10, all caches support alternate lookups for key comparisons. The primary use case for an alternate key arises when TKey is a string, and the caller must compute and materialize a new key instance at runtime to query the cache resulting in a string allocation. Alternate lookups enable use of ReadOnlySpan<char> to avoid heap allocations.

Code Sample

ICache<string, int> cache = new ConcurrentLru<string, int>(1, 1024, StringComparer.Ordinal);

IAlternateLookup<ReadOnlySpan<char>, string, int> alternate = cache.GetAlternateLookup<ReadOnlySpan<char>>();

ReadOnlySpan<char> altKey = "42".AsSpan();

bool found = alternate.TryGet(altKey, out var value);

If the comparer is not compatible, GetAlternateLookup<TAlternateKey> throws InvalidOperationException. Use the TryGet... forms when compatibility is not guaranteed.

The cache still stores string keys. That means a miss that inserts a new item must eventually create a string key. Use GetOrAdd so the cache creates the actual key only on cache miss where it is passed to the value factory:

ReadOnlySpan<char> altKey = "42".AsSpan();

int value = alternate.GetOrAdd(altKey, actualKey => int.Parse(actualKey));

Clone this wiki locally