Indexers (this[])
Part of the Object Oriented Programming section of Coddy's C# journey — lesson 37 of 70.
Indexers let you access elements in your class using array-like bracket notation. Instead of calling a method like collection.GetItem(0), you can write the more intuitive collection[0].
You define an indexer using the this keyword with square brackets:
public class Sentence
{
private string[] words;
public Sentence(string text)
{
words = text.Split(' ');
}
public string this[int index]
{
get { return words[index]; }
set { words[index] = value; }
}
}Now you can access words naturally:
Sentence s = new Sentence("Hello World");
Console.WriteLine(s[0]); // Hello
s[1] = "C#";
Console.WriteLine(s[1]); // C#Indexers aren't limited to integers. You can use any type as the index parameter, making them useful for dictionary-like access:
public string this[string key]
{
get { return dictionary[key]; }
set { dictionary[key] = value; }
}Like properties, indexers can be read-only (omit the setter) or include validation logic in their accessors. They're ideal when your class wraps a collection or when bracket notation makes the code more readable.
Challenge
EasyLet's build a Playlist class that lets you access songs using intuitive bracket notation, just like working with an array. You'll create a music playlist where songs can be retrieved and updated by their position using an indexer.
You'll organize your code across two files:
Playlist.cs: Create aPlaylistclass in theMusicnamespace that wraps an internal collection of songs and provides array-like access through an indexer. Your playlist should have:- A private string array to store song titles
- A constructor that accepts a comma-separated string of song titles and splits it into the internal array
- An indexer using
this[int index]that allows both getting and setting songs at a specific position - A read-only property
Countthat returns the number of songs in the playlist - A method
GetAllSongs()that returns all songs joined by" | "
Program.cs: In your main file, create a playlist from input, then use the indexer to access and modify songs. Demonstrate both reading songs by index and updating a song at a specific position.
You will receive three inputs:
- A comma-separated list of song titles (e.g.,
Song A,Song B,Song C) - An index to retrieve (integer)
- A new song title to replace the song at that same index
Print the output in this format:
Total songs: {Count}
Song at index {index}: {song title}
After update: {GetAllSongs()}For example, if the inputs are Rock Anthem,Jazz Vibes,Pop Hit, 1, and Blues Classic, the output should be:
Total songs: 3
Song at index 1: Jazz Vibes
After update: Rock Anthem | Blues Classic | Pop HitNotice how the indexer lets you access playlist[1] to get "Jazz Vibes" and then assign playlist[1] = "Blues Classic" to update it - much more natural than calling methods like GetSongAt(1) or SetSongAt(1, "Blues Classic")!
Cheat sheet
Indexers allow you to access elements in your class using array-like bracket notation (collection[0]) instead of method calls.
Define an indexer using the this keyword with square brackets:
public class Sentence
{
private string[] words;
public Sentence(string text)
{
words = text.Split(' ');
}
public string this[int index]
{
get { return words[index]; }
set { words[index] = value; }
}
}Usage example:
Sentence s = new Sentence("Hello World");
Console.WriteLine(s[0]); // Hello
s[1] = "C#";
Console.WriteLine(s[1]); // C#Indexers can use any type as the index parameter, not just integers:
public string this[string key]
{
get { return dictionary[key]; }
set { dictionary[key] = value; }
}Like properties, indexers can be read-only (omit the setter) or include validation logic in their accessors.
Try it yourself
using System;
using Music;
class Program
{
public static void Main(string[] args)
{
// Read inputs
string songList = Console.ReadLine();
int index = Convert.ToInt32(Console.ReadLine());
string newSong = Console.ReadLine();
// TODO: Create a Playlist object from the songList
// TODO: Print the total number of songs using the Count property
// TODO: Print the song at the given index using the indexer
// TODO: Update the song at the given index using the indexer
// TODO: Print all songs after the update using GetAllSongs()
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator