Luka Horvat
Luka Horvat

Reputation: 4402

Execute code before the called function is executed

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.

Upvotes: 5

Views: 3373

Answers (4)

Roger
Roger

Reputation: 1950

MbCache might be what you're looking for.

Upvotes: 0

Seth Flowers
Seth Flowers

Reputation: 9190

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#

Upvotes: 0

Aliostad
Aliostad

Reputation: 81660

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

Upvotes: 0

jason
jason

Reputation: 241631

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

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

Upvotes: 3

Related Questions