Getting type information at runtime in C Sharp (C#) - Time & Space Complexity
When we get type information at runtime, the program checks details about an object while it runs.
We want to know how the time needed grows as the program asks about more objects.
Analyze the time complexity of the following code snippet.
object[] items = new object[n];
for (int i = 0; i < n; i++)
{
Type t = items[i].GetType();
Console.WriteLine(t.Name);
}
This code loops through an array of objects and prints each object's type name.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling
GetType()on each object in the array. - How many times: Once for each of the
nobjects in the array.
As the number of objects grows, the program checks each one's type once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to GetType() |
| 100 | 100 calls to GetType() |
| 1000 | 1000 calls to GetType() |
Pattern observation: The number of operations grows directly with the number of objects.
Time Complexity: O(n)
This means the time needed grows in a straight line as the number of objects increases.
[X] Wrong: "Getting type information is instant and does not depend on the number of objects."
[OK] Correct: Each object's type must be checked separately, so more objects mean more work.
Understanding how runtime type checks scale helps you write efficient code and explain your reasoning clearly.
"What if we cached the type information for each object? How would the time complexity change?"