Simple Reusable .NET Caching Example Code in C#

Posted written by Paul Seal on September 06, 2016 .NET Framework C#

Why is caching important?

Caching is important because it can speed up your website or application. Why spend time and resources by needless calls to the database each time a user visits a page or uses an app?

Here is an example for you to read and use yourself.

using System;
using System.Runtime.Caching;

namespace CodeShare.Web.App_Code.Helpers
{
    public static class Caching
    {
        /// <summary>
        /// A generic method for getting and setting objects to the memory cache.
        /// </summary>
        /// <typeparam name="T">The type of the object to be returned.</typeparam>
        /// <param name="cacheItemName">The name to be used when storing this object in the cache.</param>
        /// <param name="cacheTimeInMinutes">How long to cache this object for.</param>
        /// <param name="objectSettingFunction">A parameterless function to call if the object isn't in the cache and you need to set it.</param>
        /// <returns>An object of the type you asked for</returns>
        public static T GetObjectFromCache<T>(string cacheItemName, int cacheTimeInMinutes, Func<T> objectSettingFunction)
        {
            ObjectCache cache = MemoryCache.Default;
            var cachedObject = (T)cache[cacheItemName];
            if (cachedObject == null)
            {
                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(cacheTimeInMinutes);
                cachedObject = objectSettingFunction();
                cache.Set(cacheItemName, cachedObject, policy);
            }
            return cachedObject;
        }
    }
}

Usage

int resultOfExpensiveQuery = GetObjectFromCache<int>("resultOfExpensiveQuery", 10, CallSlowQueryFromDatabase);

Parameters

The above code accepts 3 parameters. The first one is the name. When storing an object in the cache, it uses a name, so you can call it later or replace it later.

The next parameter is the cache time in minutes. This tells the application how long to store the object in the cache for.

The last parameter is the clever part. This is a delegate function. This gets called if the object isn't in the cache so the object can be set and stored in the cache. You can change this delegate function to accept parameters into it.

Generic method

The last thing to note is the use of T in the angled brackets and inside the method. This makes it a generic method. When you call the method you can tell it what Type T is.
It will return your cached object back in the form of whatever you specified T as.

A good use for this code would be the site navigation. There is no point recreating it for every page view or every user.

Real world example

To see an example of this code being used, have a look at my site navigation model post.