CSharp - Create Indexers for Sentence class

Introduction

Consider the following program and output.

When you define an indexer, the name of property is this.

We used index arguments like arrays.

We can treat the instances of a class or struct or an interface as arrays.

The this keyword is used to refer the instances.

All the modifiers-private, public, protected, internal-can be used for indexers just like properties.

The return type may be any valid C# data type.

We can create a type with multiple indexers, each with different types of parameters.

We can create read-only indexers by eliminating the set accessor.

Demo

using System;
class Program/*w  w w  .j  ava 2s  . com*/
{
    class MySentence
    {
        string[] wordsArray;
        public MySentence(string mySentence)
        {
            wordsArray = mySentence.Split();
        }
        public string this[int index]
        {
            get
            {
                return wordsArray[index];
            }
            set
            {
                wordsArray[index] = value;
            }
        }
    }
    static void Main(string[] args)
    {
        string mySentence = "This is a nice day.";
        MySentence sentenceObject = new MySentence(mySentence);
        for (int i = 0; i < mySentence.Split().Length; i++)
        {
            Console.WriteLine("\t sentenceObject[{0}]={1}", i, sentenceObject[i]);
        }
    }
}

Result

Related Quiz