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

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

Choose your learning style9 modes available
Time Complexity: Generic class declaration
O(n)
Understanding Time Complexity

Let's see how the time it takes to use a generic class changes as we work with more data.

We want to know how the program's steps grow when we create and use many generic objects.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


public class Box<T>
{
    private T content;

    public Box(T content)
    {
        this.content = content;
    }

    public T GetContent()
    {
        return content;
    }
}

// Using the generic class
var boxes = new List<Box<int>>();
for (int i = 0; i < n; i++)
{
    boxes.Add(new Box<int>(i));
}

This code defines a generic class that holds one item of any type. Then it creates many boxes holding integers.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop that creates and adds n generic Box objects.
  • How many times: Exactly n times, once for each item.
How Execution Grows With Input

Each time we add one more box, the program does one more creation and one more add operation.

Input Size (n)Approx. Operations
10About 10 creations and adds
100About 100 creations and adds
1000About 1000 creations and adds

Pattern observation: The work grows directly with the number of boxes we create.

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of boxes, the time to create and add them roughly doubles too.

Common Mistake

[X] Wrong: "Using a generic class makes the program slower because it adds extra work for each item."

[OK] Correct: The generic class itself does not add extra loops or repeated work; the main cost comes from how many items you create and add, not from using generics.

Interview Connect

Understanding how loops and object creation affect time helps you explain your code clearly and shows you know how programs grow with data size.

Self-Check

"What if we changed the loop to add boxes in nested loops (two loops inside each other)? How would the time complexity change?"