All the examples I can find about Func<> and Action<> are simple as in the one below where you see how they technically work but I would like
One thing I use it for is Caching of expensive method calls that never change given the same input:
public static Func Memoize(this Func f)
{
Dictionary values;
var methodDictionaries = new Dictionary>();
var name = f.Method.Name;
if (!methodDictionaries.TryGetValue(name, out values))
{
values = new Dictionary();
methodDictionaries.Add(name, values);
}
return a =>
{
TResult value;
if (!values.TryGetValue(a, out value))
{
value = f(a);
values.Add(a, value);
}
return value;
};
}
The default recursive fibonacci example:
class Foo
{
public Func Fibonacci = (n) =>
{
return n > 1 ? Fibonacci(n-1) + Fibonacci(n-2) : n;
};
public Foo()
{
Fibonacci = Fibonacci.Memoize();
for (int i=0; i<50; i++)
Console.WriteLine(Fibonacci(i));
}
}