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

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

Choose your learning style9 modes available
Time Complexity: Indexer declaration
O(1)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

Accessing an element by index takes the same time no matter how big the array is.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time to get or set an item stays constant as the collection grows.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding that indexers provide quick access helps you explain how collections work efficiently in real programs.

Self-Check

"What if the indexer accessed a linked list instead of an array? How would the time complexity change?"