markpsmith
markpsmith

Reputation: 4918

Delegate with parameter passed as a method parameter - how to access the delegate arg?

I'm trying to modify a delegate (itself passed as a parameter) to accept an additional parameter. This is the original method signature:

public static T GetCacheItem<T>(String key, Func<T> cachePopulate)

I've modified it to look like this:

public static T GetCacheItem<T>(String key, Func<string, T> cachePopulate)

How do I use the new string parameter? In the method code I can see that cachePopulate() is now expecting string arg, but what is it? what do I actually pass to cachePopulate()as the argument?

UPDATE:

In the pursuit of brevity, I probably didn't explain myself very well. Perhaps I should have asked how to call the updated version of the method. Anyway, the comments helped me understand that the additional delegate parameter is actually passed as an additional parameter of the GetCacheItem method, like so:

public static T GetCacheItem<T>(String key, string newparam, Func<string, T> cachePopulate)
{
    ...
    cachePopulate(newparam);
}

I was convinced that just adding it to the delegate method signature should have worked!

Upvotes: 0

Views: 70

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500575

I suspect you want:

public static T GetCacheItem<T>(String key, Func<string, T> cachePopulate)
{
    // TODO: Try to get it from the cache

    // But if not...
    T result = cachePopulate(key);
    // TODO: Cache it
    return result;
}

But basically, you need to decide the meaning of the input to the delegate.

Upvotes: 2

Related Questions