Params Parameter Modifier in C# with Example

Params Parameter Modifier in C# with Example
Params Parameter Modifier in C# with Example

An another parameter modifier is params keyword.  Like out and ref parameter modifier in C#, we have to use it in method declaration, but we don’t need to use params keyword while passing the method arguments.  Params keyword is only used in front of arrays and it should be the last parameter in your method declaration.  You cannot use more than 1 params modifier in method declaration.  Due to params modifier, you can pass variable number of comma separated method arguments, which means there is no need to create any kind of array.  It completely depends upon your choice, how you want to use it whether by passing any array or comma separated values.  Params modifier makes the method parameter optional, which means even if you do not pass any argument for it, the items in that array by default will be 0.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hello
{     

    class Program
    {
        static void Main(string[] args)
        {
           //variables
            int num1 = 10;
            int num2 = 20;

            calculation(num1, num2, 30, 40, 50);
        }

        //Calculation method
        public static void calculation(int num1, int num2, params int[] numbers)
        {
            Console.Write("{0}, {1}, ",num1, num2 );

            foreach (int number in numbers)
            {
                Console.Write("{0} ,", number);
            }
        }
    }
}

Output:

10, 20, 30 ,40 ,50 ,