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

Generic method declaration in C Sharp (C#) - Time & Space Complexity

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

Scenario Under Consideration

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

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

As the number of items grows, the method prints more lines, doing more work.

Input Size (n)Approx. Operations
1010 print operations
100100 print operations
10001000 print operations

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items.

Common Mistake

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

Interview Connect

Understanding how generic methods scale helps you explain your code clearly and shows you know how to write flexible, efficient programs.

Self-Check

"What if we changed the method to print only every other item? How would the time complexity change?"