Can I make a function accepting generic functions as a parameter?

Say I'm benchmarking a bunch of different functions, and I just want to call one function to run function foo n times.

When all the functions have the same return type, you can just do

static void benchmark(Func<ReturnType> function, int iterations)
{
    Console.WriteLine("Running {0} {1} times.", function.Method.Name, iterations);
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();
    for (int i = 0; i < iterations; ++i)
    {
        function();
    }
    stopwatch.Stop();
    Console.WriteLine("Took {0} to run {1} {2} times.", stopwatch.Elapsed, function.Method.Name, iterations);
}

but what if the the functions I'm testing have different return types? Can I accept functions with a generic type? I tried usingFunc <T> but it doesn't work.

Jon Skeet
people
quotationmark

You can make it generic, certainly:

static void Benchmark<T>(Func<T> function, int iterations)

You might also want to overload it to accept Action, for void methods.

people

See more on this question at Stackoverflow