Caching in C#/.Net

I wanted to ask you what is the best approach to implement a cache in C#? Is there a possibility by using given .NET classes or something like that? Perhaps something like a dictionary that will remove some entries, if it gets too large, but where whose entries won't be removed by the garbage collector?


Solution 1:

If you are using .NET 4 or superior, you can use MemoryCache class.

Solution 2:

If you're using ASP.NET, you could use the Cache class (System.Web.Caching).

Here is a good helper class: c-cache-helper-class

If you mean caching in a windows form app, it depends on what you're trying to do, and where you're trying to cache the data.

We've implemented a cache behind a Webservice for certain methods
(using the System.Web.Caching object.).

However, you might also want to look at the Caching Application Block. (See here) that is part of the Enterprise Library for .NET Framework 2.0.