MVC3 caching refactored

by david 11. September 2011 23:21

I was using this code here when doing some testing, but essentially the code looks like this: 

public static class CacheExtensions
{
    public static T GetOrStore<T>(this Cache cache, string key, Func<T> generator)
    {
        var result = cache[key];
        if (result == null)
        {
            result = generator();
            cache[key] = result;
        }
        return (T)result;
    }
}

...but I realised that it wasn’t actually doing much in the way of processing, and I wondered if it could be written more compactly.  So this is what I came up with:

 

public static class CacheExtensions

{

    public static T GetOrStore<T>(this Cache cache, string key, Func<T> generator) where T: class

    {

        return (cache[key] ?? (cache[key] = generator())) as T;

    }
}

As an old C programmer, I still like it when things can be done in a single line of code.

 

About the author

David

I'm a C# developer having worked with .Net since it was in beta.  Before that I mainly worked in C and C++.  I have been developing commercial software for more than 20 years.  I also mess around with microprocesors, but that's just for fun.  I live near Cambridge, England and at the moment I'm contracted to one of the departments at Cambridge University.

Tag cloud