C# - Param Array

In C#, a "param array" is a feature that allows you to pass a variable number of arguments of the same data type to a method. This is useful when you want to create a method that can accept a varying number of arguments without having to explicitly define each one. You declare a param array using the params keyword followed by the data type of the arguments you want to accept.

Here's a simple example of how to use a param array in C#:


using System;

class Program
{
    static void Main()
    {
        // Call the SumNumbers method with different numbers of arguments
        int sum1 = SumNumbers(1, 2, 3, 4);
        int sum2 = SumNumbers(5, 10, 15);

        Console.WriteLine("Sum1: " + sum1);
        Console.WriteLine("Sum2: " + sum2);
    }

    // Define a method that takes a param array of integers
    static int SumNumbers(params int[] numbers)
    {
        int sum = 0;

        // Loop through the numbers and calculate the sum
        foreach (int num in numbers)
        {
            sum += num;
        }

        return sum;
    }
}
    

Output:


Sum1: 10
Sum2: 30

In this example, we have a SumNumbers method that takes a param array of integers. You can see that we can call this method with a different number of integer arguments, and it will calculate the sum of all the numbers passed in. The params keyword allows us to pass a variable number of arguments to the method, making the code more flexible and concise.

Points to Remember:

In C#, a param array is a feature that simplifies working with methods that can accept a variable number of arguments of the same data type. Here are some important points to remember:

  1. Purpose: Param arrays allow you to pass a variable number of arguments to a method.
  2. Flexible: They make your methods flexible, allowing callers to provide different numbers of arguments.
  3. Keyword: Declare a param array using the params keyword followed by the data type of the arguments.
  4. Array-Like Behavior: Inside the method, the param array behaves like an array and can be used with loops and array operations.
  5. Simplified Code: Param arrays simplify code by avoiding the need for method overloads with different argument counts.
  6. Example Usage: Create methods that can calculate sums, averages, or perform other operations on varying numbers of inputs.
  7. Variety of Arguments: Call the method with different numbers of arguments, making your code adaptable.
  8. No-Argument Option: You can also call the method with no arguments, and it will work correctly.
  9. Return Value: The method processes the arguments and returns the result, enhancing code versatility.
  10. Saves Coding Time: Param arrays save coding time and effort by allowing you to create more flexible methods without writing multiple versions.