1

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;
TomDane
  • 1,010
  • 10
  • 25
  • 1
    As the [docs](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.caching.memorycache?view=netframework-4.7.2) say, _"The MemoryCache class is a concrete implementation of the abstract ObjectCache class."_ – stuartd Mar 22 '19 at 17:05
  • @stuartd that part makes sense. My confusion is why use the abstract class in your type declaration rather than the concrete one. – TomDane Mar 22 '19 at 17:14
  • 1
    I suspect people do it because that's what's in the documentation example. – stuartd Mar 22 '19 at 17:20

3 Answers3

7

It's similar to declaring a variable or receiving a parameter of type Stream rather than FileStream or MemoryStream: the flexibility of not having to care which implementation you have.

ObjectCache is the base class of MemoryCache. At instantiation, you're creating a specific implementation, but elsewhere in your code, it shouldn't matter which implementation you have. What matters is the common interface provided by the base class. You can change the instantiation to create a different type and the code that uses the cache doesn't have to be modified.

madreflection
  • 4,744
  • 3
  • 19
  • 29
7

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.

Dean Kuga
  • 11,878
  • 8
  • 54
  • 108
  • 1
    Good point. By the same logic though, should all properties be of type "object" rather than "string" or "int"? – TomDane Mar 22 '19 at 19:48
  • 1
    No, because those are essential data types all of which (with the exception of string) are value types, not reference types and strong typing is one of the main characteristics of the framework... – Dean Kuga Mar 22 '19 at 20:00
  • 1
    @DeanKuga, This is closer related to Dependency Injection than Liskov's. You want to be coupled to the object which provides the most functionality with the least limitiations. – johnny 5 Mar 26 '19 at 15:28
1

ObjectCache is a abstract class so you cant directly instantiate it and demonstrates how you should build a Cache that adheres to the rules the person who wrote ObjectCache wants you to obey.

So that MemoryCache inherits from ObjectCache. For everyday use you would use MemoryCashe. But if you want to your own you could inherit from objectCashe and write your own methods.

public class MemoryCache : ObjectCache, 
IEnumerable, IDisposable