Hello! Recently I began to study delegates and decided to try them in practice. I wrote a method for calculating the average execution time of a method:

public delegate void FunctionDelegate(); static public long SpeedTest(FunctionDelegate del, int numberIterations) { var stopWatch = new Stopwatch(); var listValue = new List<long>(); for (var index = 0; index < numberIterations; index++) { stopWatch.Restart(); del(); stopWatch.Stop(); listValue.Add(stopWatch.ElapsedMilliseconds); } return listValue.Sum() / listValue.Count; } 

And the question arose, is it possible to make such a delegate so that any method can be shoved into it, and then even any parameters passed?

Something like that:

 public delegate Object FunctionDelegate(params object[] args); 

    1 answer 1

    Not. You are wrong, you should think in the direction of generics.

    Writing a delegate that accepts an arbitrary number of arguments is completely impossible. The reason is simple: if this were possible, and a function that takes, say, 1 parameter is written to this delegate, how can the compiler make sure that you cannot call it with two parameters?

    There are no functions in .NET that accept an arbitrary number of parameters. Function

     void test(params object[] p) { /* ... */ } 

    takes one parameter, and the list of objects in the array for you turns caring compiler.

    What you really need to do is wrap an arbitrary function in lambda:

     static public double SpeedTest(Action a, int numberIterations) { var stopWatch = new Stopwatch(); var listValue = new List<double>(); for (var index = 0; index < numberIterations; index++) { stopWatch.Restart(); a(); stopWatch.Stop(); listValue.Add(stopWatch.ElapsedMilliseconds); } return listValue.Average(); } double f (double x, double y) { return Math.Sqrt(x * x + y * y); } double x = 1, y = 1; var averageSpeed = SpeedTest(() => { var z = f(x, y); x = y; y = z; }, 10000);