---
title: "How do you implement caching in .NET? (e.g., MemoryCache, DistributedCache, Redis)"  
description: "How do you implement caching in .NET? (e.g., MemoryCache, DistributedCache, Redis)"  
author: "Anubhav Sharma"  
published: 2025-04-02  
updated: 2025-04-02  
canonical: https://www.mindstick.com/interview/34023/how-do-you-implement-caching-in-dot-net-e-g-memorycache-distributedcache-redis  
category: "cache"  
tags: ["cache", "programming help"]  
reading_time: 4 minutes  

---

# How do you implement caching in .NET? (e.g., MemoryCache, DistributedCache, Redis)

Caching in .NET can be implemented in several ways, depending on your application's needs. Here are the common caching mechanisms:

#### 1. In-Memory Caching (MemoryCache)

Useful for small-scale, short-lived caching within a single application instance.

**Implementation Using** `MemoryCache`

```cs
using System;
using System.Runtime.Caching;

class Program
{
    static void Main()
    {
        MemoryCache cache = MemoryCache.Default;
        string cacheKey = "myKey";
        string cachedData = cache[cacheKey] as string;

        if (cachedData == null)
        {
            cachedData = "Hello, World!"; // Expensive operation result
            cache.Set(cacheKey, cachedData, DateTimeOffset.UtcNow.AddMinutes(10));
        }

        Console.WriteLine(cachedData);
    }
}
```

- **Pros:** Fast, easy to implement.
- **Cons:** Not suitable for multi-instance applications (data is lost when the app restarts).

#### 2. Distributed Caching (`IDistributedCache`)

Suitable for multi-instance applications, microservices, or cloud environments.

**Implementation Using** `IDistributedCache` **(SQL Server, Redis, or In-Memory)**

```cs
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var services = new ServiceCollection();
        services.AddDistributedMemoryCache(); // Replace with AddStackExchangeRedisCache() for Redis
        var provider = services.BuildServiceProvider();
        var cache = provider.GetRequiredService<IDistributedCache>();

        string cacheKey = "myKey";
        byte[] cachedData = await cache.GetAsync(cacheKey);

        if (cachedData == null)
        {
            string data = "Hello, Distributed Cache!";
            byte[] dataBytes = Encoding.UTF8.GetBytes(data);
            await cache.SetAsync(cacheKey, dataBytes, new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
            });

            Console.WriteLine("Cached: " + data);
        }
        else
        {
            Console.WriteLine("From Cache: " + Encoding.UTF8.GetString(cachedData));
        }
    }
}
```

- **Pros:** Works across multiple instances, supports various providers (SQL, Redis).
- **Cons:** Requires additional setup and configuration.

#### 3. Redis Caching (`StackExchange.Redis`)

Best for high-performance, scalable applications.

## Implementation Using Redis

```cs
using StackExchange.Redis;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        ConnectionMultiplexer redis = await ConnectionMultiplexer.ConnectAsync("localhost");
        IDatabase db = redis.GetDatabase();

        string cacheKey = "myKey";
        string cachedData = await db.StringGetAsync(cacheKey);

        if (cachedData == null)
        {
            cachedData = "Hello, Redis!";
            await db.StringSetAsync(cacheKey, cachedData, TimeSpan.FromMinutes(10));
            Console.WriteLine("Cached: " + cachedData);
        }
        else
        {
            Console.WriteLine("From Cache: " + cachedData);
        }
    }
}
```

- **Pros:** Scalable, supports persistence, widely used in cloud environments.
- **Cons:** Requires Redis setup and maintenance.

## Choosing the Right Cache

| **Caching Type** | **Use Case** |
| --- | --- |
| `MemoryCache` | Simple, single-instance apps |
| `IDistributedCache` (SQL, Redis, etc.) | Multi-instance apps, ASP.NET Core apps |
| `StackExchange.Redis` | High-performance distributed caching |

## Answers

### Answer by Anubhav Sharma

Caching in .NET can be implemented in several ways, depending on your application's needs. Here are the common caching mechanisms:

#### 1. In-Memory Caching (MemoryCache)

Useful for small-scale, short-lived caching within a single application instance.

**Implementation Using** `MemoryCache`

```cs
using System;
using System.Runtime.Caching;

class Program
{
    static void Main()
    {
        MemoryCache cache = MemoryCache.Default;
        string cacheKey = "myKey";
        string cachedData = cache[cacheKey] as string;

        if (cachedData == null)
        {
            cachedData = "Hello, World!"; // Expensive operation result
            cache.Set(cacheKey, cachedData, DateTimeOffset.UtcNow.AddMinutes(10));
        }

        Console.WriteLine(cachedData);
    }
}
```

- **Pros:** Fast, easy to implement.
- **Cons:** Not suitable for multi-instance applications (data is lost when the app restarts).

#### 2. Distributed Caching (`IDistributedCache`)

Suitable for multi-instance applications, microservices, or cloud environments.

**Implementation Using** `IDistributedCache` **(SQL Server, Redis, or In-Memory)**

```cs
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var services = new ServiceCollection();
        services.AddDistributedMemoryCache(); // Replace with AddStackExchangeRedisCache() for Redis
        var provider = services.BuildServiceProvider();
        var cache = provider.GetRequiredService<IDistributedCache>();

        string cacheKey = "myKey";
        byte[] cachedData = await cache.GetAsync(cacheKey);

        if (cachedData == null)
        {
            string data = "Hello, Distributed Cache!";
            byte[] dataBytes = Encoding.UTF8.GetBytes(data);
            await cache.SetAsync(cacheKey, dataBytes, new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
            });

            Console.WriteLine("Cached: " + data);
        }
        else
        {
            Console.WriteLine("From Cache: " + Encoding.UTF8.GetString(cachedData));
        }
    }
}
```

- **Pros:** Works across multiple instances, supports various providers (SQL, Redis).
- **Cons:** Requires additional setup and configuration.

#### 3. Redis Caching (`StackExchange.Redis`)

Best for high-performance, scalable applications.

## Implementation Using Redis

```cs
using StackExchange.Redis;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        ConnectionMultiplexer redis = await ConnectionMultiplexer.ConnectAsync("localhost");
        IDatabase db = redis.GetDatabase();

        string cacheKey = "myKey";
        string cachedData = await db.StringGetAsync(cacheKey);

        if (cachedData == null)
        {
            cachedData = "Hello, Redis!";
            await db.StringSetAsync(cacheKey, cachedData, TimeSpan.FromMinutes(10));
            Console.WriteLine("Cached: " + cachedData);
        }
        else
        {
            Console.WriteLine("From Cache: " + cachedData);
        }
    }
}
```

- **Pros:** Scalable, supports persistence, widely used in cloud environments.
- **Cons:** Requires Redis setup and maintenance.

## Choosing the Right Cache

| **Caching Type** | **Use Case** |
| --- | --- |
| `MemoryCache` | Simple, single-instance apps |
| `IDistributedCache` (SQL, Redis, etc.) | Multi-instance apps, ASP.NET Core apps |
| `StackExchange.Redis` | High-performance distributed caching |


---

Original Source: https://www.mindstick.com/interview/34023/how-do-you-implement-caching-in-dot-net-e-g-memorycache-distributedcache-redis

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
