Indexers in C#

Introduction:

Indexers are location indicators and are used to access class objects,just like accessing elements in an array.they are useful in cases where a class is a container for other objects.here example  uses indexers and makes an array of 15 values,stores a few values in the arrayand the null values of array from 12 position are stored with the words "empty".

 Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace IndexersExample

{

    class indexersEx

    {

        private string[] TechCompanies = new string[14];

        public string this[int indexval]

        {

            get

            {

                if (indexval < 0 || indexval >= 11)

                    return "empty";

                else

                    return TechCompanies[indexval];

            }

            set

            {

                if (!(indexval < 0 || indexval >= 11))

                    TechCompanies[indexval] = value;

            }

        }

    }

    class theMainClass

    {

        public static void Main()

        {

            indexersEx Obj = new indexersEx();

 

            Obj[0] ="MCN";

            Obj[3] ="ACCENTURE";

            Obj[5] ="GENPACT";

            Obj[6] ="POLARIS SOFTWARE";

            Obj[8] = "PATNI COMPUTERS";

            Obj[10] ="MICROSOFT";

            Obj[12] ="HCL";

            Obj[14] ="FIJUTSU";

            Console.WriteLine("This is the list of IT Companies in India.\n");

            for (int i=0;i<=14;i++)

            {

                Console.WriteLine("The name of IT Company at Index {0}{1}",i,Obj[i]);

               

               

            }

        }

    }

}

Output of the program:

indexer.gif