views:

101

answers:

3

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?

+6  A: 

You probably want:

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

Usage:

AddToCache<Person>(p, 10000, "Person", 
       () => new PersonService().GetPersonById(1));
leppie
The answer to the question title is that the `Delegate` class represents any func or delegate, but yes, this is probably what they want. +1
Rob Fonseca-Ensor
+1  A: 

Like this:

public static void AddToCache<T>(T model, double millisecs, string cacheId, Func<T> getValueFunction ) where T : class
{
  // if miss:
  var person = getValueFunction.Invoke();
}

The call would look like:

AddToCache( p , 1, "Person", () => new PersonService().GetPersonById(1) );
tanascius
Yeah, works! Thanks very much....
Michel
+1  A: 

You might want to read this blog post: Get Your Func On . It discusses the problem you are solving with the same approach.

Giorgi