Review a generated search cache key

from Records
C# 14 / .NET 10 advanced 10 min 5 issues to find

Review this generated record against the cache-key contract.

Build a stable cache key that isolates tenants, compares filter contents in order, normalizes the current query, requires a positive page, and stays safe in a dictionary.

csharp
using System.Collections.Generic;

public sealed record SearchKey(
    string Query,
    List<string> Filters)
{
    public int Page { get; set; } = 1;
    public string Normalized { get; } = Query.Trim().ToUpperInvariant();
}

public static class SearchCache
{
    private static readonly Dictionary<SearchKey, string> Cache = new();
    private static readonly SearchKey Template = new("", []);

    public static string Load(string tenantId, string query, List<string> filters, int page)
    {
        SearchKey key = Template with { Query = query, Filters = filters, Page = page };
        if (Cache.TryGetValue(key, out string? hit)) return hit;
        string value = $"{tenantId}:{key.Normalized}:{filters.Count}:{page}";
        Cache[key] = value;
        return value;
    }
}

generated code is illustrative, not from any one model

Open in playground
Report an error