Execute code before executing the called function

I would like to somehow mark the function (attributes?), So when it is called from anywhere, some other code receives the processing of the parameters and returns a value instead of the called function or it can let the functions execute normally.

I would use it for easy caching.

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

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

If the go function is called repeatedly with the same value (Add10 (7)), it will always give the same result (17), so it makes no sense to recount every time. Naturally, I would not do this with such simple functions, but I am sure you can understand what I mean.

Does C # provide any way to do what I want? I need a way to mark the function as cached, so when someone does Add10 (16), some code is run somewhere first to check the dictionary, we already know the value Add10 16 and return it, if we do, we calculate keep and if we do not.

+5
source share
4 answers

You want to remember this function. Here is one way:

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

+3
source

Instead of a function, I would provide a delegate Func<> :

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
0
source

As Jason mentioned, you probably want something like a memoization function.

Here's another topic: Whose responsibility is the result of the caching function / memoize?

You can also achieve this kind of functionality using principles related to aspect-oriented programming.

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

Aspect Oriented C # Programming

0
source

MbCache may be what you are looking for.

0
source

All Articles