0Pricing
C# Academy · Lesson

Caching Serialized Objects

Store and retrieve complex objects.

Caching Serialized Objects is a free C# Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Caching More Than Strings

Real apps cache objects, not just strings. Since IDistributedCache stores bytes, you must serialize your object to a byte/string representation, and deserialize on the way out. JSON is the usual choice.

Serializing With System.Text.Json

Use System.Text.Json to turn an object into a JSON string, then store it with SetStringAsync.

using System.Text.Json;

var product = new Product { Id = 1, Name = "Coffee", Price = 4.5m };
string json = JsonSerializer.Serialize(product);
await _cache.SetStringAsync("product:1", json);

Deserializing On Read

On read, fetch the JSON string and deserialize it back into your type, remembering to handle the cache-miss null.

string json = await _cache.GetStringAsync("product:1");
if (json is null) return null;
Product product = JsonSerializer.Deserialize<Product>(json);

A Reusable Generic Helper

Wrap the serialize/deserialize logic in extension methods so callers cache any type cleanly.

public static async Task SetAsync<T>(
    this IDistributedCache cache, string key, T value,
    DistributedCacheEntryOptions options)
{
    string json = JsonSerializer.Serialize(value);
    await cache.SetStringAsync(key, json, options);
}

The Generic Get Helper

The matching getter deserializes back to T, returning default on a miss.

public static async Task<T> GetAsync<T>(
    this IDistributedCache cache, string key)
{
    string json = await cache.GetStringAsync(key);
    return json is null ? default : JsonSerializer.Deserialize<T>(json);
}

A GetOrCreate Pattern

Combine cache-aside with serialization in one helper: return the cached object, or run a factory, cache its result, and return it.

public static async Task<T> GetOrCreateAsync<T>(
    this IDistributedCache cache, string key,
    Func<Task<T>> factory, DistributedCacheEntryOptions options)
{
    var existing = await cache.GetAsync<T>(key);
    if (existing is not null) return existing;
    var created = await factory();
    await cache.SetAsync(key, created, options);
    return created;
}

Using GetOrCreate

The call site becomes a one-liner that hides all the caching mechanics.

var product = await _cache.GetOrCreateAsync(
    "product:1",
    () => _repository.LoadProductAsync(1),
    new DistributedCacheEntryOptions
    {
        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(15)
    });

Serializer Options

Reuse a single JsonSerializerOptions instance (for example camelCase, ignore nulls) to keep cached payloads consistent and small, and to avoid allocating options repeatedly.

private static readonly JsonSerializerOptions JsonOptions = new()
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    DefaultIgnoreCondition =
        System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
};

Versioning Cached Shapes

If a cached type changes shape, old JSON may fail to deserialize. Include a version segment in the key (e.g. product:v2:1) so a deploy naturally bypasses incompatible entries.

Keep Payloads Lean

Cache only the fields you need. Smaller payloads mean less network and memory use in Redis, and faster serialization on every read and write.

Mind Serialization Cost

Serialization is not free. For very hot paths consider compact formats or caching pre-rendered results, and always measure to confirm the cache is a net win.

Quick Check

Test caching serialized objects.

Recap

To cache objects, serialize them (usually JSON via System.Text.Json) on write and deserialize on read. Generic SetAsync<T>/GetAsync<T> and a GetOrCreateAsync helper hide the mechanics and implement cache-aside cleanly. Reuse JsonSerializerOptions, version cache keys when shapes change, keep payloads lean, and measure serialization cost on hot paths.

Frequently asked questions

Is the “Caching Serialized Objects” lesson free?

Yes — the full text of “Caching Serialized Objects” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “Caching Serialized Objects”?

Store and retrieve complex objects. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Caching Serialized Objects” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. IDistributedCache Abstraction
  2. Connecting to Redis
  3. Cache Patterns and Expiration
  4. Caching Serialized Objects
← Back to C# Academy