Params keyword for variable arguments in C Sharp (C#) - Time & Space Complexity
When a method accepts a variable number of arguments using the params keyword, it can handle many inputs flexibly.
We want to understand how the time to run the method changes as we give it more arguments.
Analyze the time complexity of the following code snippet.
public void PrintNumbers(params int[] numbers)
{
foreach (int num in numbers)
{
Console.WriteLine(num);
}
}
This method prints each number passed to it, no matter how many numbers are given.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the
numbersarray. - How many times: Once for each number passed to the method.
As you give more numbers, the method prints more lines, doing more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print actions |
| 100 | 100 print actions |
| 1000 | 1000 print actions |
Pattern observation: The work grows directly with the number of inputs; double the inputs, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of arguments given.
[X] Wrong: "Using params makes the method run instantly no matter how many arguments."
[OK] Correct: The method still processes each argument one by one, so more arguments mean more work and more time.
Understanding how variable arguments affect performance shows you can think about how code scales, a useful skill in real projects and interviews.
"What if the method used recursion instead of a loop to process the params array? How would the time complexity change?"