Windows apps
Collapse the table of content
Expand the table of content
Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Array::ForEach<T> Method (array<T>^, Action<T>^)

 

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

Namespace:   System
Assembly:  mscorlib (in mscorlib.dll)

public:
generic<typename T>
static void ForEach(
	array<T>^ array,
	Action<T>^ action
)

Parameters

array
Type: array<T>^

The one-dimensional, zero-based Array on whose elements the action is to be performed.

action
Type: System::Action<T>^

The Action<T> to perform on each element of array.

Type Parameters

T

The type of the elements of the array.

Exception Condition
ArgumentNullException

array is null.

-or-

action is null.

The Action<T> is a delegate to a method that performs an action on the object passed to it. The elements of array are individually passed to the Action<T>.

This method is an O(n) operation, where n is the Length of array.

The following example shows how to use ForEach<T> to display the squares of each element in an integer array.

using namespace System;

public ref class SamplesArray
{
public:
    static void Main()
    {
        // create a three element array of integers
        array<int>^ intArray = gcnew array<int> {2, 3, 4};

        // set a delegate for the ShowSquares method
        Action<int>^ action = gcnew Action<int>(ShowSquares);

        Array::ForEach(intArray, action);
    }

private:
    static void ShowSquares(int val)
    {
        Console::WriteLine("{0:d} squared = {1:d}", val, val*val);
    }
};

int main()
{
    SamplesArray::Main();
}

/*
This code produces the following output:

2 squared = 4
3 squared = 9
4 squared = 16
*/

.NET Framework
Available since 2.0
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Return to top
Show:
© 2017 Microsoft