Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using array of Action() in a lambda expression

Tags:

c#

I want to do some performance measurement for a method that does some work with int arrays, so I wrote the following class:

public class TimeKeeper
{
    public TimeSpan Measure(Action[] actions)
    {
        var watch = new Stopwatch();
        watch.Start();
        foreach (var action in actions)
        {
            action();
        }
        return watch.Elapsed;
    }
}

But I can not call the Measure mehotd for the example below:

var elpased = new TimeKeeper();
elpased.Measure(
    () =>
    new Action[]
        {
            FillArray(ref a, "a", 10000),
            FillArray(ref a, "a", 10000),
            FillArray(ref a, "a", 10000)
        });

I get the following errors:

Cannot convert lambda expression to type 'System.Action[]' because it is not a delegate type
Cannot implicitly convert type 'void' to 'System.Action'
Cannot implicitly convert type 'void' to 'System.Action'
Cannot implicitly convert type 'void' to 'System.Action'

Here is the method that works with arrays:

private void FillArray(ref int[] array, string name, int count)
{
    array = new int[count];

    for (int i = 0; i < array.Length; i++)
    {
        array[i] = i;
    }

    Console.WriteLine("Array {0} is now filled up with {1} values", name, count);
}

What I am doing wrong?

like image 769
Saeid Yazdani Avatar asked Dec 26 '22 23:12

Saeid Yazdani


1 Answers

Measure expects its first argument to be an Action[], not a lambda that returns an Action[]. And the actions array expects you to pass delegates, while you are in fact calling FillArray.

You probably want this:

elpased.Measure
(
    new Action[]
    {
        () => FillArray(ref a, "a", 10000),
        () => FillArray(ref a, "a", 10000),
        () => FillArray(ref a, "a", 10000)
    }
);
like image 166
user703016 Avatar answered Jan 14 '23 01:01

user703016