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?"
Practice
What is the main purpose of declaring a generic class in C# using <T>?
Solution
Step 1: Understand generic class purpose
Generic classes use type parameters to work with any data type, improving code reuse and safety.Step 2: Compare options with generic concept
Only To allow the class to work with any data type safely correctly states that generics allow safe use with any data type.Final Answer:
To allow the class to work with any data type safely -> Option AQuick Check:
Generic class purpose = safe, reusable code [OK]
- Thinking generics restrict to one type
- Believing generics improve speed by skipping checks
- Confusing generics with automatic class creation
Which of the following is the correct syntax to declare a generic class named Box with one type parameter?
?
Solution
Step 1: Recall generic class syntax
Generic classes use angle brackets with type parameters:class ClassName<T>.Step 2: Check each option
public class Box<T> { } matches correct syntax. Options A, B, and D have syntax errors or wrong symbols.Final Answer:
public class Box<T> { } -> Option BQuick Check:
Generic syntax = class Name<T> [OK]
- Using parentheses instead of angle brackets
- Adding parentheses after class name
- Using square brackets instead of angle brackets
What will be the output of the following C# code?
public class Container<T> {
public T Value;
public Container(T value) { Value = value; }
public override string ToString() => $"Value: {Value}";
}
var intBox = new Container<int>(10);
var strBox = new Container<string>("Hello");
Console.WriteLine(intBox);
Console.WriteLine(strBox);Solution
Step 1: Understand class behavior
The class stores a value of type T and overrides ToString() to print "Value: {Value}".Step 2: Trace output of Console.WriteLine
intBox.ToString() returns "Value: 10" and strBox.ToString() returns "Value: Hello".Final Answer:
Value: 10 Value: Hello -> Option AQuick Check:
ToString override prints value with prefix [OK]
- Expecting variable names instead of values
- Ignoring ToString() override
- Thinking type constraints are required here
Identify the error in this generic class declaration and fix it:
public class Pair<T, U>
{
public T First;
public U Second;
public Pair(T first, U second)
{
First = first;
Second = second;
}
}
var p = new Pair<string>(5, "test");Solution
Step 1: Check instance creation syntax
Generic classes require type arguments when instantiated unless using C# 7.1+ with target-typed new.Step 2: Identify missing type arguments
The code usesnew Pair<string>(5, "test")without specifying<int, string>, causing error.Final Answer:
Missing type arguments when creating instance: use new Pair<int, string>(5, "test") -> Option CQuick Check:
Generic instantiation needs type args [OK]
- Omitting type arguments on new
- Thinking generic classes can't have multiple parameters
- Changing constructor parameter order unnecessarily
You want to create a generic class Cache<TKey, TValue> that stores key-value pairs and only allows reference types for TValue. Which declaration is correct?
Solution
Step 1: Understand type constraints
To restrict a generic type to reference types, usewhere Type : class.Step 2: Apply constraint to TValue
The question requiresTValueto be a reference type, so constraint applies toTValue.Final Answer:
public class Cache<TKey, TValue> where TValue : class { } -> Option DQuick Check:
Reference type constraint = where TValue : class [OK]
- Applying constraint to wrong type parameter
- Using 'struct' instead of 'class' for reference types
- Omitting constraints when needed
Ready to prove it?
Pass the test and this pattern moves unknown
