Params In C#

Params are an important concept in C#. We have different ways to pass parameters and arguments in C#. We can pass different types of arguments during the function calling depending upon the type of parameter we have passed during function declaration. But sometimes we do not know how many arguments we will pass during function calling and that is when params come into the picture. Using params we can pass n number of arguments during function calling without passing n parameters.

public void Display(params string[] names) {
    foreach(string items in names) {
        Console.WriteLine(items);
    }
}

Now we can pass n number of arguments during function "Display" calling.

static void Main(string[] args) {
    Program obj = new Program();
    Console.WriteLine("Passing 4 arguments");
    obj.Display("Steve", "John", "Dom", "Stark");
    Console.WriteLine();
    Console.WriteLine("Passing 5 arguments");
    obj.Display("Danes", "Wikings", "Saxons", "Dutch", "Irish");
    Console.WriteLine();
    Console.WriteLine("Passing 6 arguments");
    obj.Display("Goa", "Pune", "Kanpur", "Bhopal", "Delhi", "Kolkata");
    Console.ReadLine();
}

and the complete program looks like this,

using System;
namespace ParamPractice {
    internal class Program {
        public void Display(params string[] names) {
            foreach(string items in names) {
                Console.WriteLine(items);
            }
        }
        static void Main(string[] args) {
            Program obj = new Program();
            Console.WriteLine("Passing 4 arguments");
            obj.Display("Steve", "John", "Dom", "Stark");
            Console.WriteLine();
            Console.WriteLine("Passing 5 arguments");
            obj.Display("Danes", "Wikings", "Saxons", "Dutch", "Irish");
            Console.WriteLine();
            Console.WriteLine("Passing 6 arguments");
            obj.Display("Goa", "Pune", "Kanpur", "Bhopal", "Delhi", "Kolkata");
            Console.ReadLine();
        }
    }
}

Output

Passing 4 arguments
Steve
John
Dom
Stark

Passing 5 arguments
Danes
Wikings
Saxons
Dutch
Irish

Passing 6 arguments
Goa
Pune
Kanpur
Bhopal
Delhi
Kolkata

Some important points about params in C#:

  • The parameter type must be a single-dimensional array.
  • You can pass a comma-separated list of arguments of the type of the array elements.
  • You can pass an array of arguments of the specified type.
  • You can pass no arguments. If you send no arguments, the length of the params list is zero.
  • No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.