Variable Arguments in C#

C# Variable Arguments

In C#, variable arguments, also known as variable-length parameter lists. It provides a way to define methods that can accept a varying number of arguments of different types. This feature allows flexibility in method invocation and is particularly useful when the number of arguments or their types is not known in advance.

params keyword allows a method to accept a variable number of arguments of a specified type. This is particularly useful when the exact number of arguments a method will receive is unknown at design time. It has the following syntax:

public static void ProcessNumbers(params int[] numbers)
    {
        // Method body
    }

Example:

using System;
public class Example
{
    public static void Main(string[] args)
    {
        DisplayItems("Apple", "Banana", "Cherry");
        DisplayItems("Red", "Green");
        DisplayItems(); // No arguments
    }

    public static void DisplayItems(params string[] items)
    {
        if (items.Length == 0)
        {
            Console.WriteLine("No items to display.");
            return;
        }

        Console.WriteLine("List of items:");
        foreach (string item in items)
        {
            Console.WriteLine($"- {item}");
        }
    }
}

Note:

  • Only one params keyword is allowed in a method signature.
  • The params parameter must be the last parameter in the method’s parameter list.
  • The params parameter must be a one-dimensional array.
  • You can pass zero or more arguments to a method with a params parameter.