Search code examples
c#.netmemorycacheobjectcache

In .NET, why is ObjectCache the preferred type over MemoryCache?


So many examples of using the memory cache in .NET (including the official docs) instantiate it with:

private readonly ObjectCache memoryCache = MemoryCache.Default;

Is there any reason to prefer this over:

private readonly MemoryCache memoryCache = MemoryCache.Default;

Solution

  • The reason to prefer ObjectCache over MemoryCache is the L in SOLID...

    Liskov substitution principle:

    Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

    ObjectCache is replaceable by any of its subtypes including MemoryCache while MemoryCache is not replaceable by anything forcing you into a specific implementation.