CHASH Tutorial



C# params


C# params Keyword

The params keyword allows a method to accept a variable number of arguments as a single parameter, which is treated as an array inside the method.

Key Features

  • Only one params parameter is allowed per method.
  • It must be the last parameter in the method signature.
  • Arguments can be passed individually or as an array.

Example: Using params to Sum Numbers

class Program
{
    // Method accepts variable number of integers
    static int Sum(params int[] numbers)
    {
        int total = 0;
        foreach (int num in numbers)
        {
            total += num;
        }
        return total;
    }

    static void Main()
    {
        Console.WriteLine(Sum(1, 2, 3));          // Output: 6
        Console.WriteLine(Sum(10, 20, 30, 40));   // Output: 100

        int[] arr = {5, 15, 25};
        Console.WriteLine(Sum(arr));               // Output: 45
    }
}
  

Usage Tips

  • Great for methods where the number of arguments can vary.
  • Improves code readability by avoiding overloads for different argument counts.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review