Indexer In C#

Introduction

Indexers are instance members that allow class, struct and interfaces to be indexed just like an array, and the class behaves similar to a virtual array.

Indexer has no name but "get" and "set" accessor are  like properties.

Suppose we have a private string array with the name Days, that holds the names of the weekdays and I want to access the names of the days using index. To achieve this, we use Indexer as shown below.
  1. public class Indexers {  
  2.     public string[] Days = {  
  3.         "Sunday",  
  4.         "Monday",  
  5.         "Tuesday",  
  6.         "Wednesday",  
  7.         "Thursday",  
  8.         "Friday",  
  9.         "Saturday"  
  10.     };  
  11.     public string this[int index] {  
  12.         get {  
  13.             return Days[index];  
  14.         }  
  15.     }  
  16. }  
  17. public class IndexerClient {  
  18.     public static void Main(string[] args) {  
  19.         Indexers IOb = new Indexers();  
  20.         Console.WriteLine(IOb[0]); // sunday  
  21.         Console.ReadKey();  
  22.     }  
  23. }  
Ebook Download
View all
Learn
View all