What if your custom objects could be accessed as easily as arrays with just one simple feature?
Why Indexer declaration in C Sharp (C#)? - Purpose & Use Cases
Imagine you have a collection of items, like a list of books, and you want to get or set a book by its position. Without indexers, you must write separate methods like GetBookAt(int index) and SetBookAt(int index, Book book). This feels like using a remote control with too many buttons for simple tasks.
Manually writing methods to access items by position is slow and clunky. It makes your code longer and harder to read. You also lose the natural feeling of using square brackets [] like with arrays. This can cause confusion and mistakes, especially when working with collections often.
Indexer declaration lets you use square brackets [] directly on your class instances to get or set items by index. It makes your class behave like an array or list, making your code cleaner, shorter, and easier to understand. It feels natural and intuitive, just like accessing elements in built-in collections.
public Book GetBookAt(int index) { return books[index]; }
public void SetBookAt(int index, Book book) { books[index] = book; }public Book this[int index] {
get => books[index];
set => books[index] = value;
}Indexer declaration enables your custom classes to be accessed like arrays, making your code simpler and more expressive.
Think of a playlist app where you want to get or change songs by their position. Using an indexer, you can write playlist[2] to get the third song, just like you do with arrays.
Manual methods for indexed access are verbose and unnatural.
Indexer declaration lets you use [] syntax on your own classes.
This makes code cleaner, easier to read, and more intuitive.
Practice
Solution
Step 1: Understand what an indexer does
An indexer lets you access elements in an object using square brackets, similar to arrays.Step 2: Compare options with this definition
Only To allow objects to be accessed like arrays using square brackets describes this behavior correctly.Final Answer:
To allow objects to be accessed like arrays using square brackets -> Option BQuick Check:
Indexer = access with [] [OK]
- Confusing indexers with methods
- Thinking indexers create new objects
- Mixing indexers with constants
Solution
Step 1: Recall indexer syntax
An indexer uses the keywordthiswith a parameter list in square brackets and definesgetand/orsetaccessors inside braces.Step 2: Check each option
public int this[int index] { get; set; } matches the correct syntax exactly. public int indexer(int index) { get; set; } uses a method-like name, which is incorrect. public int this[index] { get; set; } misses the type in the parameter. public int this[int index] get set; misses braces and semicolons.Final Answer:
public int this[int index] { get; set; } -> Option DQuick Check:
Indexer syntax = this[type param] { get; set; } [OK]
- Using method name instead of 'this'
- Omitting parameter type
- Missing braces around get/set
class Sample {
private int[] data = {10, 20, 30};
public int this[int i] {
get { return data[i]; }
set { data[i] = value; }
}
}
var s = new Sample();
s[1] = 50;
Console.WriteLine(s[1]);Solution
Step 1: Understand the indexer behavior
The indexer accesses the private arraydata. Settings[1] = 50;changesdata[1]from 20 to 50.Step 2: Check the output of
This prints the updated value at index 1, which is 50.Console.WriteLine(s[1])Final Answer:
50 -> Option AQuick Check:
Indexer set changes value, output = 50 [OK]
- Assuming original value prints
- Confusing indexer with method call
- Expecting compilation error
public string this[int index]
{
get { return data[index]; }
set data[index] = value;
}Solution
Step 1: Review accessor syntax
Bothgetandsetaccessors must have braces enclosing their bodies.Step 2: Locate the error
Thesetaccessor lacks braces arounddata[index] = value;, causing a syntax error.Final Answer:
Missing braces around set accessor body -> Option CQuick Check:
Accessor bodies need braces { } [OK]
- Omitting braces in set accessor
- Wrong return type assumption
- Thinking parameter name is restricted
Solution
Step 1: Understand requirements for read/write access
The indexer must have bothgetandsetaccessors to allow reading and writing by index.Step 2: Evaluate each option
public string this[int i] { get { return names[i]; } } only hasget, so no writing. public string this[int i] { set { names[i] = value; } } only hasset, so no reading. public string this[int i] { get { return names[i]; } set { names[i] = value; } } has bothgetandsetwith int index parameter, which is correct. public string this[string name] { get { return name; } set { name = value; } } uses a string parameter, which does not match the requirement to access by index.Final Answer:
public string this[int i] { get { return names[i]; } set { names[i] = value; } } -> Option AQuick Check:
Read/write indexer needs both get and set [OK]
- Defining only get or only set
- Using wrong parameter type
- Confusing indexer parameter with property
Ready to prove it?
Pass the test and this pattern moves unknown
