C# Params

In C#, the params keyword is used in method declarations to specify that a parameter can take a variable number of arguments. It allows you to pass an arbitrary number of arguments of the same type to a method.

Here’s the syntax for using the params keyword:

public void MyMethod(params dataType[] parameterName)
{
    // Method body
}

Let’s break down the syntax:

  • public: This is the access modifier, indicating the visibility of the method. It can be public, private, protected, or other valid access modifiers.
  • void: This is the return type of the method. In this case, the method doesn’t return any value.
  • MyMethod: This is the name of the method. You can choose any valid identifier.
  • params: This is the keyword that indicates that the following parameter can take a variable number of arguments.
  • dataType[]: This is the type of the parameter, followed by square brackets indicating an array of that type. The parameter can accept zero or more arguments of this type.
  • parameterName: This is the name of the parameter. You can choose any valid identifier.

Here’s an example usage of the params keyword:

public void PrintNumbers(params int[] numbers)
{
    foreach (int number in numbers)
    {
        Console.WriteLine(number);
    }
}

// Usage
PrintNumbers(1, 2, 3);   // Output: 1 2 3
PrintNumbers(4, 5, 6, 7);   // Output: 4 5 6 7
PrintNumbers();   // Output: (nothing)

In the example above, the PrintNumbers method can accept any number of integer arguments. Inside the method, the numbers parameter is treated as an array, allowing you to loop through and perform operations on each individual argument.