What are parameter/param arrays in C#?

CsharpProgrammingServer Side Programming

C# param arrays help if you are not sure of the number of arguments passed as a parameter, while declaring a method.

The following is the syntax through which you can use the params keyword −

public int function_name(params int[] variable_name) {}

Here us an example to learn about param arrays in C# −

Example

 Live Demo

using System;

namespace Program {
   class ParamArray {
      public int AddElements(params int[] arr) {
         int sum = 0;

         foreach (int i in arr) {
            sum += i;
         }
         return sum;
      }
   }

   class Demo {
      static void Main(string[] args) {
         ParamArray app = new ParamArray();
         int sum = app.AddElements(300, 250, 350, 600, 120);
   
         Console.WriteLine("The sum is: {0}", sum);
         Console.ReadKey();
      }
   }
}

Output

The sum is: 1620
raja
Published on 08-Aug-2018 13:05:19
Advertisements