Letβs go through indexers in C# β a feature that makes objects behave like arrays.
π 1. What is an Indexer?
-
An indexer allows an object of a class or struct to be accessed using array-like syntax (
obj[index]
). -
Essentially, it defines how the object responds to the
[]
operator. -
Useful when your class wraps a collection or you want custom access logic.
π 2. Syntax of an Indexer
public class SampleCollection
{
private string[] data = new string[5];
// Indexer
public string this[int index]
{
get { return data[index]; }
set { data[index] = value; }
}
}
-
this[int index]
β defines the indexer -
get
β called when accessingobj[index]
-
set
β called when assigningobj[index] = value
π 3. Example Usage
SampleCollection collection = new SampleCollection();
// Using indexer like an array
collection[0] = "Hello";
collection[1] = "World";
Console.WriteLine(collection[0]); // Hello
Console.WriteLine(collection[1]); // World
- Notice how
collection[0]
behaves like a normal array, but the logic is defined in your class.
π 4. Key Points
-
Indexers can be overloaded with different parameter types (int, string, etc.)
-
No name is needed for an indexer; itβs always
this[...]
-
Can be read-write, read-only, or write-only depending on which accessors you implement
Example: String-based Indexer
public string this[string key]
{
get { return data[Array.IndexOf(data, key)]; }
}
π 5. Analogy
-
Think of an indexer as a custom array:
-
Your object acts like an array
-
You can control how data is stored or retrieved
-
π 6. Benefits
-
Encapsulates internal data structures
-
Provides array-like access to objects without exposing the underlying collection
-
Supports custom logic when getting or setting values
β Tip:
-
Use indexers when your class represents a collection or needs array-like access with custom logic.
-
They are often used in wrappers around dictionaries, lists, or custom data structures.