Generic class declaration in C Sharp (C#) - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: The loop that creates and adds
ngeneric Box objects. - How many times: Exactly
ntimes, once for each item.
Each time we add one more box, the program does one more creation and one more add operation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 creations and adds |
| 100 | About 100 creations and adds |
| 1000 | About 1000 creations and adds |
Pattern observation: The work grows directly with the number of boxes we create.
Time Complexity: O(n)
This means if you double the number of boxes, the time to create and add them roughly doubles too.
[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.
Understanding how loops and object creation affect time helps you explain your code clearly and shows you know how programs grow with data size.
"What if we changed the loop to add boxes in nested loops (two loops inside each other)? How would the time complexity change?"