How to define param arrays in C#?


While declaring a method, you are not sure of the number of arguments passed as a parameter. C# param arrays (or parameter arrays) come into help at such times.

This is how you can use the param −

public int AddElements(params int[] arr) { }

The following is the complete example −

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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 20-Jun-2020

84 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements