An indexer allows an object to be indexed like an array. - CSharp Custom Type

CSharp examples for Custom Type:Indexer

Introduction

A one dimensional indexer has the following syntax

element-type this[int index] {
   get {
      // return the value specified by index
   }
   set {
      // set the value specified by index
   }
}

Demo Code

using System;/*www. j av  a 2s  . 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;
            }
         }
      }
      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]);
         }
      }
}

Result


Related Tutorials