Generics/Delegates and Passing functions with parameters
.net, c#, delegates, function, generics
Solution
If parameter of functions will fill outside of GetGlobalCacheitem method, you can defraud calling function with another delegate like this:
public static T GetGlobalCacheitem<T>(Func<T> populateCacheCall)
and call it:
Func<int ,int , object> tempPopulateCacheCall=(a,b)=>new object();
GetGlobalCacheitem(()=>tempPopulateCacheCall(1,2))
Or any other function signature with vary parameter
Func<int , object> tempPopulateCacheCall=(a)=>new object();
GetGlobalCacheitem(()=>tempPopulateCacheCall(1))
Problem
I am trying to create a generic CacheManager that I can use all over my application which will ensure that all the management of cache items is done in a consistent manner and adheres to some cache access patterns. This will be used to cache all types of objects as necessary. I understand I can use a delegate to pass in functions to a method, which you can see below. ``` public static T GetGlobalCacheitem( Func<int ,int , T> populateCacheCall ) { string cacheKey = "test"; var cachedObject = CacheFactory<T>.GlobalCache.GetGlobalCacheItem(cacheKey); if (cachedObject == null) { cachedObject = populateCacheCall(); CacheFactory<T>.GlobalCache.AddGlobalCacheItem(cachedObject, cacheKey); } return cachedObject; } ``` however I have 2 problems. Most of the functions I want to pass in to populate the cache will themselves have paramaters that they need. As in the above instance this is a method which will take two int paramaters. The first question is how can I also pass in the paramaters that I want the function to be invoked with as they will not be know in this cachehandler, that will be known outside of this. ALso this relates to the next question two, and how can I do this in an approach will work work regardless of the number of parameters the function requires (if any) The second problem is that a lot of the functions which I will need to pass in to populate the cache items will be varied , in that some will have no paramaters , some will have one , some may have more than one and the types of each of these paramaters are going to vary. So how would I be able to enable this to work without having to define a function with all possible signatures which will cover every possible combination of functions which pay me used.