NathanTempelman
NathanTempelman

Reputation: 1387

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.

Upvotes: 2

Views: 124

Answers (3)

Jared
Jared

Reputation: 2816

 static void BenchmarkFoo<T>(Func<T> foo, int n) where T :new() <-- condition on T

Depending on what you want to do with that return value you may need to put conditions on your generic.

Upvotes: 1

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73502

static void benchmarkFoo<T>(Func<T> foo, int n)
                         ^       ^

Note the generic parameters in above mentioned places. That is enough.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503080

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.

Upvotes: 6

Related Questions