Method overloading in C Sharp (C#) - Time & Space Complexity
We want to understand how the time it takes to run overloaded methods changes as input size grows.
How does choosing different method versions affect the work done?
Analyze the time complexity of the following code snippet.
public class Calculator
{
public int Add(int a, int b) => a + b;
public int Add(int a, int b, int c) => a + b + c;
public int Add(int[] numbers)
{
int sum = 0;
foreach (var num in numbers)
sum += num;
return sum;
}
}
This code shows three methods named Add with different inputs: two numbers, three numbers, or an array of numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop through the array in the third Add method.
- How many times: Once for each number in the input array.
When using the array version, the work grows as we add more numbers to sum.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items to add.
Time Complexity: O(n)
This means the time to add numbers grows in a straight line with how many numbers you have.
[X] Wrong: "All overloaded methods take the same time regardless of input size."
[OK] Correct: The methods with fixed inputs run quickly, but the one that sums an array takes longer as the array grows.
Understanding how different method versions affect performance helps you explain your code choices clearly and confidently.
"What if the Add method used recursion to sum the array instead of a loop? How would the time complexity change?"