C# delegate or Func for 'all methods'?

Posted by Michel on Stack Overflow See other posts from Stack Overflow or by Michel
Published on 2010-04-23T07:59:27Z Indexed on 2010/04/23 8:03 UTC
Read the original article Hit count: 274

Filed under:
|
|
|
|

Hi,

i've read something about Func's and delegates and that they can help you to pass a method as a parameter. Now i have a cachingservice, and it has this declaration:

public static void AddToCache<T>(T model, double millisecs, string cacheId) where T : class
public static T GetFromCache<T>(string cacheId) where T : class

So in a place where i want to cache some data, i check if it exists in the cache (with GetFromCache) and if not, get the data from somewhere, and the add it to the cache (with AddToCache)

Now i want to extend the AddToCache method with a parameter, which is the class+method to call to get the data Then the declaration would be like this

public static void AddToCache<T>(T model, double millisecs, string cacheId, Func/Delegate methode) where T : class

Then this method could check wether the cache has data or not, and if not, get the data itself via the method it got provided.

Then in the calling code i could say:

AddToCache<Person>(p, 10000, "Person", new PersonService().GetPersonById(1));
AddToCache<Advert>(a, 100000, "Advert", new AdvertService().GetAdverts(3));

What i want to achieve is that the 'if cache is empty get data and add to cache' logic is placed on only one place.

I hope this makes sense :)

Oh, by the way, the question is: is this possible?

© Stack Overflow or respective owner

Related posts about generics

Related posts about anonymous-function