What are overloaded indexers in C#?


An indexer in C# allows an object to be indexed such as an array. When an indexer for a class is defined, 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.

The following is an example of overloaded indexers in C# −

Example

 Live Demo

using System;
namespace IndexerApplication {
   class IndexedNames {
      private string[] namelist = new string[size];
      static public int size = 10;
   
      public IndexedNames() {
         for (int i = 0; i < size; i++) {
            namelist[i] = "N. A.";
         }
      }
      public string this[int index] {
         get {
            string tmp;

            if( index >= 0 && index <= size-1 ) {
               tmp = namelist[index];
            } else {
               tmp = "";
            }
            return ( tmp );
         }
         set {
            if( index >= 0 && index <= size-1 ) {
               namelist[index] = value;
            }
         }
      }

      public int this[string name] {
         get {
            int index = 0;
            while(index < size) {
               if (namelist[index] == name) {
                  return index;
               }
               index++;
            }
            return index;
         }  
      }
      static void Main(string[] args) {
         IndexedNames names = new IndexedNames();
         names[0] = "John";
         names[1] = "Joe";
         names[2] = "Graham";
         names[3] = "William";
         names[4] = "Jack";
         names[5] = "Tom";
         names[6] = "Tim";
         //using the first indexer with int parameter
         for (int i = 0; i < IndexedNames.size; i++) {
            Console.WriteLine(names[i]);
         }
         //using the second indexer with the string parameter
         Console.WriteLine(names["Nuha"]);
         Console.ReadKey();
      }  
   }
}

Output

John
Joe
Graham
William
Jack
Tom
Tim
N. A.
N. A.
N. A.
10

Updated on: 20-Jun-2020

439 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements