Passing methods as parameters with Func<T, TResult>

Today I found this nice feature that I like a lot: Func<T, TResult>. Basically this makes it possible to pass a method as a parameter without explicitly declaring a custom delegate.

I used it a lot in a helper class that caches the data retrieved from DB. Below I’ll leave some examples:

/// <summary>
/// Helper method for adding/retrieving a value from/to the cache.
/// </summary>
/// <param name="cacheKey">The key of the cached item</param>
/// <param name="getFromCache">True if a cached vaersion cand be returned. If false, f() will be used to get the data</param>
/// <param name="f">If the key is not found in the cache execute the f() function to retrieve the object</param>
/// <returns></returns>
private static object GetFromCache(string cacheKey, bool getFromCache, Func<object> f)
{
	object cachedItem = null;
	if (getFromCache)
		cachedItem = HttpRuntime.Cache[cacheKey];

	if (cachedItem == null)
	{
		cachedItem = f();
		if (cachedItem != null)
			HttpRuntime.Cache.Insert(cacheKey, cachedItem, null, DateTime.Now.AddSeconds(WebConfigSettings.CachingTime), TimeSpan.Zero);
	}

	return cachedItem;
}

Now, in order to get the data from the cache, if it exists, or otherwise retrieve it from DB, it’s enough to pass a key and an anonymous method that will be used in case the data is not in the cache:

public static List GetListFromDB()
{
	return (List)GetFromCache("GetListFromDB", () => new List {"aaa", "bbb", "ccc"} ); 
	//Not exactly from DB, but you get the point
}

That’s it! Simple and elegant. 🙂

Advertisements