patterncsharpMinor
Extension method to get results of type T from a cache
Viewed 0 times
methodextensiontypegetcacheresultsfrom
Problem
Are there issues of any kind with this extension method?
using System;
using System.Web;
namespace AccountingBackupWeb.CacheExtensions
{
public static class Extensions
{
public static T Get(this System.Web.Caching.Cache cache, string key, Func f) where T : class
{
T results = HttpContext.Current.Cache[key] as T;
if (results == null)
{
results = f();
HttpContext.Current.Cache[key] = results;
}
return results;
}
}
}Solution
Logically, it makes sense to me that you would want to tie a key to a Func. This method could then just take the string and then delegate the responsibility to decide how to fetch the value to another class. Also, a few nitpicky points about what is actually there. I consider using letters as variables poor practice since it gives no context as to how it will be used. I would rename "f" to something like "retrieve" or "fetch". Also, there is no guarantee that running "f" will actually give you a non null value. In that case, I doubt you would want to store null in your cache.
Context
StackExchange Code Review Q#6885, answer score: 4
Revisions (0)
No revisions yet.