RasmusW RasmusW - 1 year ago 83
C# Question

Generic function declaration in c#

I'm trying to create some stats about method call duration in a library.
Instead of wrapping each method call to the library with lines to time and track it, I want to create a generic action and function which does these recurring steps.
E.g. for methods that don't return a value, I have created this:

private readonly Action<string, Action> timedAction = (name, action) =>
var sw = Stopwatch.StartNew();
trackDuration(name, sw.ElapsedMilliseconds);

That can be invoked with
timedAction("methodname", () => lib.methodname())

I want to do something similar for methods that return a value, but obviously
can't be used for that purpose, since it can't return a value.

Is there a way to do this with a generic
, so I don't have to declare one for each combination of library method parameters?

Answer Source

Use can use a generic function like this.

private static TValue FuncHandler<TValue>(string name, Func<TValue> func)
    var sw = Stopwatch.StartNew();
    var result = func();

    trackDuration(name, sw.ElapsedMilliseconds);

    return result;

Call like this.

var result = FuncHandler("name", () => MyMethod(param1));