INDEXERS

It allows an instance of a class to be indexed and accessed as an array. When we define an index for a class then we can access the instance of this class using the array

It allows an instance of a class to be indexed and accessed as an array. When we define an index for a class then we can access the instance of this class using the array access operator([ ]).

[access_modifier] [return_type] this[argument_list]
{
     get
     {
         // get block code
     }
     set
     {
         // set block code
     }
}
using System;

namespace IndexerApplication
{

    class Indexer
    {
        private string[] namelist = new string[size];
        static public int size = 10;

        public Indexer()    //Default constructor used to assign default values but not a mandatory one
        {
            for (int i = 0; i < size; i++)
                namelist[i] = "N. A.";
        }

        public string this[int index]
        {
            get
            {
                if (index >= 0 && index <= size - 1)
                {
                    return namelist[index];
                }
                else
                {
                    return "";
                }
            }
            set
            {
                if (index >= 0 && index <= size - 1)
                {
                    namelist[index] = value;
                }
            }
        }

        static void Main(string[] args)
        {
            Indexer names = new Indexer();
            names[0] = "Teja";
            names[1] = "Vamsi";
            names[2] = "Akshay";
            names[3] = "Mona";
            names[4] = "Raj";
            names[5] = "Sunil";
            names[6] = "Rubic";

            for (int i = 0; i < Indexer.size; i++)
            {
                Console.WriteLine(names[i]);
            }
            Console.ReadKey();
        }
    }
}

Important points about indexers:

  1. Indexers can be overloaded.
  2. They look like a property but are different from Properties.
  3. A set accessor will always assign the value while the get accessor will return the value.
  4. “This” keyword is used to declare an indexer.
  5. Indexers are also known as Smart Arrays or Parameterized Property in C#.
  6. Indexers can’t be a static member.

When to Use Indexers:

  1. When we need an array of instances for a class
  2. If your class contains a list/array of values directly related to the class.

4 thoughts on “INDEXERS

Leave a Reply

Your email address will not be published. Required fields are marked *