Implementing an indexer - CSharp Custom Type

CSharp examples for Custom Type:Indexer

Introduction

To write an indexer, define a property called this, specifying the arguments in square brackets.

Demo Code

using System;//from   ww  w. j av a2 s. c o m
class Sentence
{
   string[] words = "The quick brown fox".Split();
   public string this [int wordNum]      // indexer
   {
      get { return words [wordNum];  }
      set { words [wordNum] = value; }
   }
}
class Test
{
   static void Main(){
      Sentence s = new Sentence();
      Console.WriteLine (s[3]);       // fox
      s[3] = "kangaroo";
      Console.WriteLine (s[3]);       // kangaroo
   }
}

Result

A type may declare multiple indexers, each with parameters of different types.

An indexer can also take more than one parameter:

public string this [int arg1, string arg2]
{
  get { ... }  set { ... }
}

If you omit the set accessor, an indexer becomes read-only.

Expression-bodied syntax may be used in C# 6 to shorten its definition:

public string this [int wordNum] => words [wordNum];

Related Tutorials