Abdul Saboor Abdul Saboor - 1 month ago 40
C# Question

What is difference between MemoryCache vs ObjectCache in .net 4.0?

What is difference between .NET framework 4.0

Where to use which object?


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

MemoryCache is an actual implementation of ObjectCache.

From the documentation:


Represents an object cache and provides the base methods and properties for accessing the object cache.


Represents the type that implements an in-memory cache.

Looking at the declaration for MemoryCache:

public class MemoryCache : ObjectCache, 
    IEnumerable, IDisposable

We can see that MemoryCache inherits from ObjectCache - that is, it's an cache for objects that uses Memory as its storage - this is therefore an implementation of ObjectCache.

You could write your own; for example, DatabaseCache, which could also inherit from ObjectCache but instead it would use a database as the backing storage.

For everyday use, provided it met your needs, you would use and consume a MemoryCache. If you wanted to write your own, you could inherit from ObjectCache and implement the required methods and properties. However, in reality, there is probably little practical benefit to doing this as Microsoft already make several other caching solutions available, as do many other vendors.