Create Indexers in C#

 

As we know arrays can be accessed  by index. In the same way we can access any C# class members through index by using Indexers in C#.

 

Today we discussed about how to create Indexers in C# with simple example. Indexers in C# are almost same as lists in C#.

 

Create new console project CSharpIndexers in Microsoft Visual Studio.

 

Add new class Employee with get and set method.  We access this class by using indexers in C# as shown below.

 

 

using System;

 

namespace CSharpIndexers

{

    class Program

    {

        static void Main(string[] args)

        {

            Employee objEmp = new Employee();

 

            //Add Employees

            objEmp[0] = "A1";

            objEmp[1] = "A2";

            objEmp[2] = "A3";

            objEmp[3] = "A4";

           

 

            //Get EMployees

            Console.WriteLine(objEmp[0]);

            Console.WriteLine(objEmp[1]);

            Console.WriteLine(objEmp[2]);

            Console.WriteLine(objEmp[120]);

 

            Console.ReadLine();

        }

    }

 

    class Employee

    {

        string[] _names = new string[100];

 

        public string this[int id]

        {

            get

            {

                if (id >= 0 && id < _names.Length)

                {

                    return _names[id];

                }

                else

                {

                    return "No Employee Found";

                }

            }

            set

            {

                if (id >= 0 && id < _names.Length)

                {

                    _names[id] = value;

                }

            }

        }

    }

 

}

 

As shown above in Employee class we created the indexer by using this operator. Run the application and output as below.

 

 

                                                                                                       CSharpIndexers.zip (23.50 kb)