C# Params Array

Some conditions, you are not assured about number of parameters or you want to create a method that can accept n number of parameters at run time. This situation can be handled with params type array in C#. The params keyword creates an array at run time that receives and holds n number of parameters.

static int add(params int[] allnumber)

In the above line, the allnumber variable can holds n number of parameters at runtime because it is declared with params keyword.

In below example, we are creating a function Add() that will take any number of integer parameters at run time and returns the sum of all those number. We will use params array to complete this goal in C#.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Params_Array_Example
{
    class Program
    {
        static int Add(params int[] allnumber)
        {
            int sum = 0;
            foreach (int n in allnumber)
            {
                sum = sum + n;
            }
            return sum;
        }
        static void Main(string[] args)
        {
            int sum;
            // passing three parameters
            sum = Program.Add(1, 2, 3);
            Console.WriteLine("Sum of 1,2,3 is:\t{0}", sum);
            // passing five parameters
            sum = Program.add(3, 5, 2, 6, 2);
            Console.WriteLine("Sum of 3,5,2,6,2 is:\t{0}", sum);
            Console.ReadLine();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *