Indexers in C#

Indexers in C# with Examples

In this article, I am going to discuss Indexers in C# with Examples. Please read our previous article where we discussed How to make Optional Parameters in C#. As part of this article, we will discuss what indexers are and how to create and use indexers in C#.

What are Indexers in C#?

The Indexers in C# 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 that gives access to the values of a class just like an array.

Example: Indexers in C#

Let us understand Indexers in C# with an example. Create a new console application. Create a new class file with the name Employee.cs and then copy and paste the following code into it. The following class is very straightforward; we are just declaring some properties and initializing them through the class constructor.

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;
        }
    }
}

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 the 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)
        {
            //Creating the Employee instance
            Employee emp = new Employee(101, "Pranaya", "SSE", 10000, "Mumbai", "IT", "Male");

            //Accessing Employee Properties using Indexers i.e. using Index positions
            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 you try to build the application, you will get the following error.

Indexers in C# with Examples

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 logic’s 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 in C#?

You need to use the following syntax to define an Indexer in a Class.

How to define an Indexer in C#

Let us understand the above syntax:

  1. Modifiers: The “modifiers” are nothing but the access specifiers such as public, private, protected, etc.
  2. Type: As we are dealing with the integer (ID), string (Name, Job, Department, Location, and Gender), and double (Salary) type of values, so here we need to use the “type” as Object because Object type can return any type of values.
  3. This: The “this” keyword telling that we are defining an indexer on the current class, in this case, the current class is Employee.
  4. Int index or String name: 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 the string name
  5. Get and Set: The get accessor is used for returning the value and the set accessor is used for assigning the value.
Example: Indexers in C#

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. Here, we creating an index by using the int index position so that we can access the elements by using its integer index postion. In the case of the set accessor, the parameter “value” is implicit holds the assigned value.

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();
            }
        }
    }
}

Now, let’s try to access the values like an array, and also let’s try to modify the values like an array. So, please modify modifying the Program class Main method 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[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 integer index position. So in such cases, most of the time we need to access the values by using the property name. To do so we need to use a string name instead of an int indexer. So let’s modify the Employee class to use string name as indexer 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, I am going to discuss a Real-time example of using an indexer in C#. Here, in this article, I try to explain Indexers in C# with 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 *