Using an Indexer - CSharp Custom Type

CSharp examples for Custom Type:Indexer

Introduction

The format for defining an indexer is shown here:

public dataType this[int index]
{
    get
     {
          // Do whatever you want...
          return aValue;
     }
     set
     {
          // Do whatever you want
     }
}

Demo Code

using System;/*from   ww  w  .j av  a 2  s. c  o m*/
public class SpellingList
{
   protected string[] words = new string[size];
   static public int size = 10;
   public SpellingList()
   {
      for (int x = 0; x < size; x++ )
         words[x] = String.Format("Word{0}", x);
      }
      public string this[int index]
      {
         get
         {
            string tmp;
            if( index >= 0 && index <= size-1 )
               tmp = words[index];
            else
               tmp = "";
               return ( tmp );
            }
            set
            {
               if( index >= 0 && index <= size-1 )
                  words[index] = value;
               }
            }
         }
         public class Indexer
         {
            public static void Main()
            {
               SpellingList myList = new SpellingList();
               myList[3] = "----";
               myList[4] = "Brad";
               myList[5] = "was";
               myList[6] = "Here!";
               myList[7] = "----";
               for ( int x = 0; x < SpellingList.size; x++ )
                  Console.WriteLine(myList[x]);
               }
}

Result


Related Tutorials