I initially came here just looking for an abstract memoization method for a no-parameter function. This isn't exactly an answer to the question but wanted to share my solution in case someone else came looking for the simple case.
public static class MemoizationExtensions
{
public static Func Memoize(this Func f)
{
bool hasBeenCalled = false; // Used to determine if we called the function and the result was the same as default(R)
R returnVal = default(R);
return () =>
{
// Should be faster than doing null checks and if we got a null the first time,
// we really want to memoize that result and not inadvertently call the function again.
if (!hasBeenCalled)
{
hasBeenCalled = true;
returnVal = f();
}
return returnVal;
};
}
}
If you use LinqPad you can use the following code to easily test out the functionality through the use of LinqPad's super cool Dump method.
new List>(new Func
P.S. You will need to include the MemoizationExtensions class in the code of the LinqPad script otherwise it won't work!