C# - Params Arrays



At the times, when declaring a method, we are not sure of the number of arguments passed as a parameter. In C#, a params array (or parameters array) allows us to pass a variable number of arguments to a method. We use the params keyword in the method's parameter list.

C# params Keyword

C# params keyword allows you to pass multiple values (a variable number of arguments) to a function without making an array. That means you do not need to create an array and pass array name as an argument.

Syntax

Here is the syntax of passing arguments with params keyword:

returnType FunctionName(params dataType[] parameterName)  
{  
    // Function body  
}

Example of Params Arrays

Following is the basic example of the params array. Here, the PrintNumbers method uses the params keyword to indicate that it can take a variable number of int arguments.

using System;
class Program
{
   static void Main()
   {
      PrintNumbers(1, 2, 3, 4, 5);
      PrintNumbers(10, 20, 30);
      PrintNumbers();
   }
   // Method using params array
   static void PrintNumbers(params int[] numbers)
   {
      foreach (int num in numbers)
      {
         Console.WriteLine(num);
      }
   }
}

Following is the output of the code −

1
2
3
4
5
10
20
30

Using params with Different Data Types

You can also use params keyword with different types of values such as strings, objects, or custom types.

Example

In the following example, we use the params keyword to pass multiple city names to a function, which then prints each city:

using System;

class Program {
    static void PrintCities(params string[] cities) {
        foreach (string city in cities) {
            Console.WriteLine(city);
        }
    }

    static void Main() {
        PrintCities("Delhi", "Mumbai", "Bangalore", "Chennai", "Kolkata");
    }
}

When executed, this program outputs:

Delhi
Mumbai
Bangalore
Chennai
Kolkata
Advertisements