Extension method syntax in C Sharp (C#) - Time & Space Complexity
Let's see how the time needed to run an extension method changes as the input grows.
We want to know how the number of steps changes when we use extension methods on collections.
Analyze the time complexity of the following code snippet.
public static class Extensions
{
public static int SumElements(this int[] numbers)
{
int sum = 0;
foreach (int num in numbers)
{
sum += num;
}
return sum;
}
}
This code adds a new method to arrays that sums all their numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array.
- How many times: Once for every element in the array.
As the array gets bigger, the method does more additions, one for each number.
| 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.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Extension methods make the code slower because they add extra steps."
[OK] Correct: Extension methods are just normal methods called in a special way; they don't add extra loops or slow down the process.
Knowing how extension methods work and their time cost helps you write clear and efficient code, a skill that shows you understand both style and performance.
"What if we changed the extension method to sum only the even numbers? How would the time complexity change?"