Indexers can be overloaded. - CSharp Custom Type

CSharp examples for Custom Type:Indexer

Description

Indexers can be overloaded.

Demo Code

using System;/* www .j a va2s .  com*/
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] = "!";
      names[1] = "@";
      names[2] = "$";
      names[3] = "A";
      names[4] = "D";
      names[5] = "S";
      names[6] = "R";
      for (int i = 0; i < IndexedNames.size; i++) {
         Console.WriteLine(names[i]);
      }
      Console.WriteLine(names["Nuha"]);
   }
}

Result


Related Tutorials