How to use Array.ForEach() method to performs a specified action on each element of an array in C#

1 Answer

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = new int[] { 1, 2, 3, 4, 5 };

            // action = delegate for ShowCalc method
            Action<int> action = new Action<int>(ShowCalc);

            Array.ForEach(arr, action);
        }
        private static void ShowCalc(int n)
        {
            Console.WriteLine("{0:d} : calc = {1:d}", n, n * n);
        }
    }
}


/*
run:
 
1 : calc = 1
2 : calc = 4
3 : calc = 9
4 : calc = 16
5 : calc = 25

*/

 



answered Apr 23, 2016 by avibootz
...