What are indexers in C# and when should you use them?
Learn what indexers are in C#, how to declare them with the this keyword, when to use them over methods, and see practical examples and interview questions.
Expected Interview Answer
An indexer is a special member that lets instances of a class or struct be accessed with array-like square-bracket syntax, such as 'myObject[key]', by defining a 'this[...]' accessor with get and set logic. It makes a type that wraps a collection feel like the collection itself.
You declare an indexer using the 'this' keyword followed by parameters, for example 'public T this[int index]'. It can take any parameter type, not just integers, so you can index by string keys or multiple parameters. Indexers can be read-only, write-only, or read-write, can be overloaded by parameter type, and are ideal when a type logically represents an indexed or keyed collection. Use them to expose internal storage cleanly; avoid them when a named method communicates intent better.
- Gives a type intuitive array-like access syntax
- Encapsulates internal storage behind get/set logic
- Supports keys of any type, not just integers
- Can be overloaded for multiple parameter types
- Allows validation or computation on access
- Makes custom collections feel built-in
AI Mentor Explanation
An indexer is like a scoreboard operator who fetches any batter's score when you just call out a shirt number, hiding the ledger behind the scenes. You say 'give me number 7' and get the runs instantly, exactly as an indexer lets you write 'team[7]' to reach the stored value without knowing how the roster is kept internally.
Step-by-Step Explanation
Step 1
Declare the indexer
Use the 'this' keyword with a parameter: 'public T this[int index]' inside your class or struct.
Step 2
Define get and set
Provide accessors that read from and write to internal storage, adding validation as needed.
Step 3
Choose the key type
Parameters can be int, string, or multiple values, so index by whatever key makes sense.
Step 4
Overload if useful
Declare multiple indexers with different parameter types to support several access styles.
Step 5
Use it like an array
Callers write 'obj[key]' to get or set, without seeing the underlying collection.
What Interviewer Expects
- Knowing indexers use the 'this' keyword
- That key parameters need not be integers
- Understanding get/set accessors and validation
- Awareness that indexers can be overloaded and take multiple parameters
- Judgment on when an indexer beats a named method
Common Mistakes
- Confusing an indexer with a property or a plain method
- Assuming the index must always be an integer
- Using an indexer when a named method would be clearer
- Forgetting bounds or key validation in the accessors
- Not knowing indexers can be overloaded by parameter type
Best Answer (HR Friendly)
“An indexer lets you use square brackets on your own object, like 'myList[2]', as if it were a built-in array or dictionary. You use it when your class really represents a collection of items, so the code reading it feels natural and the storage stays hidden inside the class.”
Code Example
public class WeekTemperatures
{
private readonly double[] _temps = new double[7];
public double this[int day]
{
get
{
if (day < 0 || day > 6)
throw new IndexOutOfRangeException();
return _temps[day];
}
set => _temps[day] = value;
}
}
var week = new WeekTemperatures();
week[0] = 21.5; // uses set
Console.WriteLine(week[0]); // uses get -> 21.5Follow-up Questions
- How does an indexer differ from a property?
- Can an indexer take multiple parameters? Give an example.
- How do you make an indexer read-only?
- Can indexers be overloaded, and how does the compiler pick one?
- When is a named method preferable to an indexer?
MCQ Practice
1. Which keyword declares an indexer in C#?
Indexers are declared with the 'this' keyword, e.g. 'public T this[int index]'.
2. What type can an indexer's parameter be?
Indexer parameters can be any type and there can be more than one, so you can index by string or several keys.
3. When is an indexer the best choice?
Indexers shine when a type logically wraps a collection and array-like access reads naturally.
Flash Cards
How is an indexer declared? — With the 'this' keyword: 'public T this[int index] { get; set; }'.
Must an indexer key be an integer? — No, it can be any type such as string, and can take multiple parameters.
Indexer vs property? — A property is accessed by name; an indexer is accessed with square brackets and takes parameters.
Can indexers be overloaded? — Yes, by differing parameter types or counts, like methods.