Passing arrays to methods in C#?

CsharpProgrammingServer Side Programming

To pass arrays to methods, you need to pass an array as a method argument.

int displaySum(int[] arr, int size) {
}

Now call it −

sum = d.displaySum(myArr, 5 ) ;

Example

 Live Demo

using System;

namespace Test {
   class Demo {
      int displaySum(int[] arr, int size) {
         int i;
         int sum = 0;

         for (i = 0; i < size; ++i) {
            sum += arr[i];
         }

         return sum;
      }
   
      static void Main(string[] args) {
         Demo d = new Demo();

         int [] myArr = new int[] {59, 34, 76, 65, 12, 99};
         int sum;

         sum = d.displaySum(myArr, 5 ) ;

         /* output the returned value */
         Console.WriteLine( "Sum: {0} ", sum );
         Console.ReadKey();
      }
   }
}

Output

Sum: 246
raja
Published on 20-Aug-2018 09:28:00
Advertisements