Indexers in C#

Indexers in C#

In this article, I am going to discuss Indexers in C#. As part of this article, we will discuss what indexers are and how to create and use indexers in C#.

The Indexers are the members of a class and if we define indexers in a class then the class behaves like a virtual array. So it’s a member of a class which gives access to the values of a class just like an array.

Let us understand this with an example.

Create a new console application. Create a new class file with the Name Employee and then copy and paste the following code.

namespace IndexersDemo
{
    public class Employee
    {
        //Declare the properties
        public int ID { get; set; }
        public string Name { get; set; }
        public string Job { get; set; }
        public double Salary { get; set; }
        public string Location { get; set; }
        public string Department { get; set; }
        public string Gender { get; set; }

        //Initialize the properties through constructor
        public Employee(int ID, string Name, string Job, int Salary, string Location, 
                        string Department, string Gender)
        {
            this.ID = ID;
            this.Name = Name;
            this.Job = Job;
            this.Salary = Salary;
            this.Location = Location;
            this.Department = Department;
            this.Gender = Gender;
        }
    }
}

The above class is very straightforward; we are just declaring some properties and initializing them through the class constructor.

Let’s try to create an instance of the Employee class and let’s try to consume the employee object like an array.

Let’s create another class with main method as shown below where I try to access the Employee data using index positions.

using System;
namespace IndexersDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee(101, "Pranaya", "SSE", 10000, "Mumbai", "IT", "Male");
            Console.WriteLine("EID = " + emp[0]);
            Console.WriteLine("Name = " + emp[1]);
            Console.WriteLine("Job = " + emp[2]);
            Console.WriteLine("Salary = " + emp[3]);
            Console.WriteLine("Location = " + emp[4]);
            Console.WriteLine("Department = " + emp[5]);
            Console.WriteLine("Gender = " + emp[6]);
            
            Console.ReadLine();
        }
    }
}

Now when we try to build the application, we got the following error.

Indexers in C#

This is because we cannot apply indexing directly to a class. We can do indexing on an array but we cannot do the same thing with a user-defined class like Employee. An array is a predefined class and all the logics are implemented in that class for indexing so that we can access them using indexes. But Employee is a user-defined class and we have not implemented any logic to access the class like an array.

If you want to access the class like an array then first you need to define an indexer in the class. Once you define an indexer in the class then you can start accessing the values of the class by using the index position.

How to define an Indexer:

Syntax:

Indexers in C#

The “modifiers” are nothing but the access specifiers such as public, private, protected etc.

As we are dealing with the integer (ID), string (Name. Job, Department, Location, and Gender) and double (Salary) type of value, so here we need to use the “type” as Object because Object type can return any type of values.

The “this” keyword telling that we are defining an indexer on the current class, in this case, the current class is Employee.

The int index or string name is used to specify whether you want to access the values by using its integer index position or by using string name

The get accessor is used for returning the value and the set accessor is used for assigning the value.

So, let’s create an index on the Employee class for both get and set accessor.

The complete code of the Employee class is given below.
using System;
namespace IndexersDemo
{
    public class Employee
    {
        //Declare the properties
        public int ID { get; set; }
        public string Name { get; set; }
        public string Job { get; set; }
        public double Salary { get; set; }
        public string Location { get; set; }
        public string Department { get; set; }
        public string Gender { get; set; }

        //Initialize the properties through constructor
        public Employee(int ID, string Name, string Job, int Salary, string Location, 
                        string Department, string Gender)
        {
            this.ID = ID;
            this.Name = Name;
            this.Job = Job;
            this.Salary = Salary;
            this.Location = Location;
            this.Department = Department;
            this.Gender = Gender;
        }

        public object this [int index]
        {
            //The get accessor is used for returning a value
            get
            {
                if (index == 0)
                    return ID;
                else if (index == 1)
                    return Name;
                else if (index == 2)
                    return Job;
                else if (index == 3)
                    return Salary;
                else if (index == 4)
                    return Location;
                else if (index == 5)
                    return Department;
                else if (index == 6)
                    return Gender;
                else
                    return null;
            }
            
            // The set accessor is used to assigning a value
            set
            {
                if (index == 0)
                    ID = Convert.ToInt32(value);
                else if (index == 1)
                    Name = value.ToString();
                else if (index == 2)
                    Job = value.ToString();
                else if (index == 3)
                    Salary = Convert.ToDouble(value);
                else if (index == 4)
                    Location = value.ToString();
                else if (index == 5)
                    Department = value.ToString();
                else if (index == 6)
                    Gender = value.ToString();
            }
        }
    }
}

Note: In the case of the set accessor, the parameter value is implicit holds the assigned value.

Let’s try to access the values like an array and also let’s try to modifying the values like an array as shown below by modifying the Program class.

using System;
namespace IndexersDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee(101, "Pranaya", "SSE", 10000, "Mumbai", "IT", "Male");
            Console.WriteLine("EID = " + emp[0]);
            Console.WriteLine("Name = " + emp[1]);
            Console.WriteLine("Job = " + emp[2]);
            Console.WriteLine("Salary = " + emp[3]);
            Console.WriteLine("Location = " + emp[4]);
            Console.WriteLine("Department = " + emp[5]);
            Console.WriteLine("Gender = " + emp[6]);

            emp[1] = "Kumar";
            emp[3] = 65000;
            emp[5] = "BBSR";
            Console.WriteLine("=======Afrer Modification=========");

            Console.WriteLine("EID = " + emp[0]);
            Console.WriteLine("Name = " + emp[1]);
            Console.WriteLine("Job = " + emp[2]);
            Console.WriteLine("Salary = " + emp[3]);
            Console.WriteLine("Location = " + emp[4]);
            Console.WriteLine("Department = " + emp[5]);
            Console.WriteLine("Gender = " + emp[6]);

            Console.ReadLine();
        }
    }
}

When we run the application, it gives us the below output.

Indexers in C#

But in real-time, we may have more number of properties and it’s very difficult to access the values by using the index position. So in such cases, in most of the time we need to access the values by using the property name. To do so we need to use string accessor. So let’s modify the indexer to use string name as shown below.

using System;
namespace IndexersDemo
{
    public class Employee
    {
        //Declare the properties
        public int ID { get; set; }
        public string Name { get; set; }
        public string Job { get; set; }
        public double Salary { get; set; }
        public string Location { get; set; }
        public string Department { get; set; }
        public string Gender { get; set; }

        //Initialize the properties through constructor
        public Employee(int ID, string Name, string Job, int Salary, string Location, 
                        string Department, string Gender)
        {
            this.ID = ID;
            this.Name = Name;
            this.Job = Job;
            this.Salary = Salary;
            this.Location = Location;
            this.Department = Department;
            this.Gender = Gender;
        }

        public object this [string Name]
        {
            //The get accessor is used for returning a value
            get
            {
                if (Name == "ID")
                    return ID;
                else if (Name == "Name")
                    return Name;
                else if (Name == "Job")
                    return Job;
                else if (Name == "Salary")
                    return Salary;
                else if (Name == "Location")
                    return Location;
                else if (Name == "Department")
                    return Department;
                else if (Name == "Gender")
                    return Gender;
                else
                    return null;
            }
            
            // The set accessor is used to assigning a value
            set
            {
                if (Name == "ID")
                    ID = Convert.ToInt32(value);
                else if (Name == "Name")
                    Name = value.ToString();
                else if (Name == "Job")
                    Job = value.ToString();
                else if (Name == "Salary")
                    Salary = Convert.ToDouble(value);
                else if (Name == "Location")
                    Location = value.ToString();
                else if (Name == "Department")
                    Department = value.ToString();
                else if (Name == "Gender")
                    Gender = value.ToString();
            }
        }
    }
}

Let’s test this by modify the Main method of the Program class as shown below.

using System;
namespace IndexersDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee(101, "Pranaya", "SSE", 10000, "Mumbai", "IT", "Male");
            Console.WriteLine("EID = " + emp["ID"]);
            Console.WriteLine("Name = " + emp["Name"]);
            Console.WriteLine("Job = " + emp["job"]);
            Console.WriteLine("Salary = " + emp["salary"]);
            Console.WriteLine("Location = " + emp["Location"]);
            Console.WriteLine("Department = " + emp["department"]);
            Console.WriteLine("Gender = " + emp["Gender"]);

            emp["Name"] = "Kumar";
            emp["salary"] = 65000;
            emp["Location"] = "BBSR";
            Console.WriteLine("=======Afrer Modification=========");

            Console.WriteLine("EID = " + emp["ID"]);
            Console.WriteLine("Name = " + emp["Name"]);
            Console.WriteLine("Job = " + emp["job"]);
            Console.WriteLine("Salary = " + emp["salary"]);
            Console.WriteLine("Location = " + emp["Location"]);
            Console.WriteLine("Department = " + emp["department"]);
            Console.WriteLine("Gender = " + emp["Gender"]);
            
            Console.ReadLine();
        }
    }
}
When we run the application, we get the following output

Indexers in C#

As you can see, we are not getting the data for Job, Salary and Department. This is because the indexers are case sensitive. To get or set the data properly, either we need to convert the indexer name to upper or lower case as shown below.

public object this[string Name]
{
    //The get accessor is used for returning a value
    get
    {
        if (Name.ToUpper() == "ID")
            return ID;
        else if (Name.ToUpper() == "NAME")
            return Name;
        else if (Name.ToUpper() == "JOB")
            return Job;
        else if (Name.ToUpper() == "SALARY")
            return Salary;
        else if (Name.ToUpper() == "LOCATION")
            return Location;
        else if (Name.ToUpper() == "DEPARTMENT")
            return Department;
        else if (Name.ToUpper() == "GENDER")
            return Gender;
        else
            return null;
    }

    // The set accessor is used to assigning a value
    set
    {
        if (Name.ToUpper() == "ID")
            ID = Convert.ToInt32(value);
        else if (Name.ToUpper() == "NAME")
            Name = value.ToString();
        else if (Name.ToUpper() == "JOB")
            Job = value.ToString();
        else if (Name.ToUpper() == "SALARY")
            Salary = Convert.ToDouble(value);
        else if (Name.ToUpper() == "LOCATION")
            Location = value.ToString();
        else if (Name.ToUpper() == "DEPARTMENT")
            Department = value.ToString();
        else if (Name.ToUpper() == "GENDER")
            Gender = value.ToString();
    }
}

Now if you run the application, you will get the output as expected. In the next article, we will discuss the real-time example of using indexer in C#.

SUMMARY:

In this article, I try to explain Indexers in C# with some examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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