How do I overload the [] operator in C#?

CsharpServer Side ProgrammingProgramming

The [] operator is called an indexer.

An indexer allows an object to be indexed such as an array. When you define an indexer for a class, this class behaves similar to a virtual array. You can then access the instance of this class using the array access operator ([ ]).

Indexers can be overloaded. Indexers can also be declared with multiple parameters and each parameter may be a different type. It is not necessary that the indexes have to be integers.

Example 1

static void Main(string[] args){
   IndexerClass Team = new IndexerClass();
   Team[0] = "A";
   Team[1] = "B";
   Team[2] = "C";
   Team[3] = "D";
   Team[4] = "E";
   Team[5] = "F";
   Team[6] = "G";
   Team[7] = "H";
   Team[8] = "I";
   Team[9] = "J";
   for (int i = 0; i < 10; i++){
      Console.WriteLine(Team[i]);
   }
   Console.ReadLine();
}
class IndexerClass{
   private string[] names = new string[10];
   public string this[int i]{
      get{
         return names[i];
      } set {
         names[i] = value;
      }
   }
}

Output

A
B
C
D
E
F
G
H
I
J

Example 2

Overriding []

static class Program{
   static void Main(string[] args){
      IndexerClass Team = new IndexerClass();
      Team[0] = "A";
      Team[1] = "B";
      Team[2] = "C";
      for (int i = 0; i < 10; i++){
         Console.WriteLine(Team[i]);
      }
      System.Console.WriteLine(Team["C"]);
      Console.ReadLine();
   }
}
class IndexerClass{
   private string[] names = new string[10];
   public string this[int i]{
      get{
         return names[i];
      }
      set{
         names[i] = value;
      }
   }
   public string this[string i]{
      get{
         return names.Where(x => x == i).FirstOrDefault();
      }
   }
}

Output

A
B
C
C
raja
Published on 05-Nov-2020 18:10:17
Advertisements