C# Array ForEach Action

In this chapter you will learn:

  1. Array.ForEach with a delegate
  2. Example for Array ForEach Action
  3. ForEach with your own delegate
  4. Use an Action to change the values

Description

You can enumerate using the static Array.ForEach method:

public static void ForEach<T> (T[] array, Action<T> action);

This uses an Action delegate, with this signature:

public delegate void Action<T> (T obj);

Example

Example for Array ForEach Action


using System;//from www .jav a2 s  . co m

public class MainClass{
    public static void Main(){
        int[] array = new int[] { 8, 2, 3, 5, 1, 3 };
        Array.ForEach<int>(array, delegate(int x) { Console.Write(x + " "); });
        Console.WriteLine();
    }
} 

The code above generates the following result.

We can further rewrite the code above as below.


using System;//from  w  ww. ja v a 2s .c  om
using System.Collections;

class Sample
{
  public static void Main()
  {
    Array.ForEach(new[] { 1, 2, 3 }, Console.WriteLine);
  }
}

The output:

ForEach with your own delegate


using System;    
   /* ww w .j av  a  2 s .c  o  m*/
class MyClass { 
  public int i;  
   
  public MyClass(int x) { 
    i = x; 
  }
}
  
class MainClass {       
 
  static void show(MyClass o) { 
    Console.Write(o.i + " "); 
  } 
 
  public static void Main() {       
    MyClass[] nums = new MyClass[5];  
  
    nums[0] = new MyClass(5);  
    nums[1] = new MyClass(2);  
    nums[2] = new MyClass(3);  
    nums[3] = new MyClass(4);  
    nums[4] = new MyClass(1);  
     
    Console.Write("Contents of nums: ");   
 
    // Use action to show the values. 
    Array.ForEach(nums, MainClass.show); 
 
    Console.WriteLine();   
 
  }       
}

The code above generates the following result.

Change array element in a ForEach Action


using System;    
   /* w  ww .  ja  v a2  s .  c  o  m*/
class MyClass { 
  public int i;  
   
  public MyClass(int x) { 
    i = x; 
  }
}
  
class MainClass {       
 
  static void neg(MyClass o) {  
    o.i = -o.i; 
  }  
  static void show(MyClass o) { 
    Console.Write(o.i + " "); 
  } 
  public static void Main() {       
    MyClass[] nums = new MyClass[5];  
  
    nums[0] = new MyClass(5);  
    nums[1] = new MyClass(2);  
    nums[2] = new MyClass(3);  
    nums[3] = new MyClass(4);  
    nums[4] = new MyClass(1);  
     
    // Use action to negate the values. 
    Array.ForEach(nums, MainClass.neg); 
 
     // Use action to show the values. 
    Array.ForEach(nums, MainClass.show); 
  }       
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What is Exception
  2. System exceptions
Home »
  C# Tutorial »
    C# Language »
      C# Array
C# Arrays
C# Array Length
C# Array Rank
C# Array Index
C# Multidimensional Arrays
C# Array Initialization
C# Jagged Array
C# Array foreach loop
C# Array ForEach Action