Indexer declaration in C Sharp (C#) - Time & Space Complexity
When we use an indexer in C#, we want to quickly get or set items by position.
We ask: how does the time to access an item change as the collection grows?
Analyze the time complexity of this indexer code.
public class SimpleList
{
private int[] items = new int[100];
public int this[int index]
{
get { return items[index]; }
set { items[index] = value; }
}
}
This code defines an indexer to get or set an element in an array by its position.
Look for repeated actions when using the indexer.
- Primary operation: Accessing an array element by index.
- How many times: Each access is a single direct operation, no loops involved.
Accessing an element by index takes the same time no matter how big the array is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time to get or set an item stays constant as the collection grows.
Time Complexity: O(1)
This means accessing or setting an item by index takes the same short time no matter how many items there are.
[X] Wrong: "Accessing an item by index takes longer if the list is bigger."
[OK] Correct: Arrays allow direct access, so the time does not grow with size.
Understanding that indexers provide quick access helps you explain how collections work efficiently in real programs.
"What if the indexer accessed a linked list instead of an array? How would the time complexity change?"