How to Create Indexer in C#: Syntax and Example
In C#, create an
indexer by defining a property named this with a parameter inside a class. This lets you access objects like arrays using square brackets, e.g., obj[index]. The indexer must have at least a get accessor and optionally a set accessor.Syntax
An indexer in C# looks like a property named this with one or more parameters inside square brackets. It has get and/or set accessors to read or write values.
- this[int index]: defines the index parameter type and name.
- get: returns the value at the given index.
- set: assigns a value at the given index.
csharp
public class Sample { private int[] data = new int[10]; public int this[int index] { get { return data[index]; } set { data[index] = value; } } }
Example
This example shows a class WeekDays with an indexer that stores and retrieves day names by index. It demonstrates how to use the indexer like an array.
csharp
using System; public class WeekDays { private string[] days = new string[7]; public string this[int index] { get { if (index < 0 || index >= days.Length) throw new IndexOutOfRangeException("Index out of range"); return days[index]; } set { if (index < 0 || index >= days.Length) throw new IndexOutOfRangeException("Index out of range"); days[index] = value; } } } class Program { static void Main() { WeekDays week = new WeekDays(); week[0] = "Sunday"; week[1] = "Monday"; week[2] = "Tuesday"; Console.WriteLine(week[0]); Console.WriteLine(week[1]); Console.WriteLine(week[2]); } }
Output
Sunday
Monday
Tuesday
Common Pitfalls
Common mistakes when creating indexers include:
- Not defining
getaccessor (indexer must have at leastget). - Using invalid index types (indexer parameters must be valid types like
int). - Not handling out-of-range indexes, which causes runtime errors.
- Confusing indexers with regular properties or methods.
Always validate index values inside get and set to avoid exceptions.
csharp
public class WrongIndexer { private int[] data = new int[5]; // Missing get accessor - this will cause a compile error public int this[int index] { set { data[index] = value; } } } // Correct version public class CorrectIndexer { private int[] data = new int[5]; public int this[int index] { get { return data[index]; } set { data[index] = value; } } }
Quick Reference
Indexer Cheat Sheet:
this[parameter]: defines the indexer.- Must have at least a
getaccessor. - Can have multiple parameters for complex indexing.
- Use
valuekeyword insidesetaccessor. - Validate index parameters to avoid runtime errors.
Key Takeaways
An indexer in C# lets you access class instances like arrays using square brackets.
Define an indexer with the
this keyword and at least a get accessor.Always validate index values inside the indexer to prevent runtime errors.
Indexers can have multiple parameters but usually use an integer index.
Use
value inside the set accessor to assign values.