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.