0
0
C Sharp (C#)programming~5 mins

Method overloading in C Sharp (C#) - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Method overloading
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

When using the array version, the work grows as we add more numbers to sum.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the number of items to add.

Final Time Complexity

Time Complexity: O(n)

This means the time to add numbers grows in a straight line with how many numbers you have.

Common Mistake

[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.

Interview Connect

Understanding how different method versions affect performance helps you explain your code choices clearly and confidently.

Self-Check

"What if the Add method used recursion to sum the array instead of a loop? How would the time complexity change?"