Generic method declaration in C Sharp (C#) - Time & Space Complexity
When we write a generic method, we want to know how its running time changes as the input grows.
We ask: How does the method's work increase when we give it more data?
Analyze the time complexity of the following code snippet.
public static void PrintItems<T>(T[] items)
{
for (int i = 0; i < items.Length; i++)
{
Console.WriteLine(items[i]);
}
}
This method prints each item in an array of any type.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array to print each item.
- How many times: Once for each item in the array (items.Length times).
As the number of items grows, the method prints more lines, doing more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print operations |
| 100 | 100 print operations |
| 1000 | 1000 print operations |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items.
[X] Wrong: "Generic methods run slower because they handle many types."
[OK] Correct: The generic method's speed depends on the work inside it, not on the types it handles. The loop runs the same way regardless of type.
Understanding how generic methods scale helps you explain your code clearly and shows you know how to write flexible, efficient programs.
"What if we changed the method to print only every other item? How would the time complexity change?"