5

I would like to be able to mark a function somehow (attributes maybe?) so that when it's called from anywhere, some other code gets to process the parameters and return a value instead of the called function, or can let the function execute normally.

I would use it for easy caching.

For example, if I had a function called Add10 and it would look like this:

int Add10 (int n)
{
    return n + 10;
}

If the function go called repeatedly with the same value (Add10(7)) it would always give the same result (17) so it makes no sense to recalculate every time. Naturally, I wouldn't do it with functions as simple as this but I'm sure you can understand what I mean.

Does C# provide any way of doing what I want? I need a way to mark a function as cached so that when someone does Add10(16) some code somewhere is ran first to check in a dictionary is we already know the Add10 value of 16 and return it if we do, calculate, store and return if we don't.

Luka Horvat
  • 4,283
  • 3
  • 30
  • 48
  • refer http://stackoverflow.com/questions/6180242/generating-a-unique-cache-key-based-on-method-arguments – Romil Kumar Jain May 01 '12 at 13:45
  • There is alot of threads on this here at stackoverflow, e.g. http://stackoverflow.com/questions/4929540/is-there-anyway-to-cache-function-method-in-c-sharp – abaelter May 01 '12 at 13:46

4 Answers4

3

You want to memoize the function. Here's one way:

http://blogs.msdn.com/b/wesdyer/archive/2007/01/26/function-memoization.aspx

jason
  • 236,483
  • 35
  • 423
  • 525
  • The link is unfortunately broken and it looks like that this post was deleted. At least it is not in this list from wesdyer 01/2007 https://learn.microsoft.com/en-us/archive/blogs/wesdyer/ – Darkproduct Feb 01 '22 at 11:54
0

Instead of the function, then I would expose a Func<> delegate:

Func<int, int> add10 = (n) =>
{
    // do some other work
    ...

    int result = Add10(n); // calling actual function

    // do some more perhaps even change result
    ...

    return result;

};

And then:

int res = add10(5); // invoking the delegate rather than calling function
Aliostad
  • 80,612
  • 21
  • 160
  • 208
0

Like Jason mentioned, you probably want something like function memoization.

Heres another SO thread about it: Whose responsibility is it to cache / memoize function results?

You could also achieve this sort of functionality using principles related to Aspect Oriented Programming.

http://msdn.microsoft.com/en-us/magazine/gg490353.aspx

Aspect Oriented Programming in C#

Community
  • 1
  • 1
Seth Flowers
  • 8,990
  • 2
  • 29
  • 42
0

MbCache might be what you're looking for.

Roger
  • 1,944
  • 1
  • 11
  • 17