Eleno
Eleno

Reputation: 3016

Calling ForEach with an anonymous action

Compiling this code:

           var arr = new[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 };
           arr.ForEach(x =>
                    {
                          Console.WriteLine(x);
                    });

Fails with:

error CS7036: There is no argument given that corresponds to the required formal parameter 'action' of 'Array.ForEach<T>(T[], Action<T>)'

Why?

Upvotes: 1

Views: 452

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38880

ForEach is a static method on the Array class. It is not, however, an extension method.

The documentation for the method states the following (emphasis mine):

Performs the specified action on each element of the specified array.

It takes two parameters:

  1. T[] - The one-dimensional, zero-based Array on whose elements the action is to be performed.
  2. Action<T> - The Action to perform on each element of array.

You need to call it like this:

Array.ForEach(arr, x =>
{
    Console.WriteLine(x);
});

Upvotes: 3

Related Questions