Need to inspect the values of a delegate method

I have a need to pass a delegate method with a varying number and type of parameters to another method. My hope is to be able to inspect the values of the parameters within the call.

This is my generic cache class.

public T Get<T>(Expression<Func<T>> getItemCallback) where T : class

    T item = HttpRuntime.Cache.Get(hashRepresentationOfValues) as T;
    if (item == null)
        item = getItemCallback.Compile()();
    return item;

My calls look like the following:

private DataContext db;
return cache.Get<List<SomeDBObject>>(
    () => db.SomeDBObjectCall(param1, param2, param3));

As you can see it would be extremely helpful if I could dynamically determine the values of the delegate call as they could be used as the cache-key.


So basically, you have a method with an unknown signature that you want to wrap for caching purposes. If that's the case, you will definitely want to look into a technique called Memoization

Memoization on Wikipedia In computing, memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously processed inputs.

An example of such a function in C# would be something along these lines:

static Func<A, R> Memoize(this Func<A, R> f)
    var dict = new Dictionary<A, R>();
    return (A arg)=>
        R result;
        if (!dict.TryGetValue(arg, out result))
             result = f(arg);
             dict.Add(arg, result);
        return result;

Note that the method takes a generic Func and returns a generic Func with the same signature. This way, you can effectively wrap your methods without bogging up the rest of your code. It is really seamless!

More examples here and here

Need Your Help

Using Java Dictionary...use a Hashtable?

java swing jslider

I'm a bit surprised no one has asked about this specific case, cause it's kind of a weird inconsistency in the java standard libraries:

How to terminate a process without os.kill() - OSGeo4W Python 2.5

python qt osgeo

I'm using the distribution of Python2.5.2 included in the OSGeo4W installer. This is a 32-bit distribution running on Windows 7. Although PyQt is not installed by default by the OSGeo4W installer...