Indexers Real-Time Example in C#

Indexers Real-Time Example in C#

In this article, I will discuss Indexers Real-Time Example in C#. Please read our previous article before proceeding to this article where we discussed what indexers are and how to create and use indexers in C# with some examples.

As we already discussed in our previous article that an indexer is a member of a class that enables an object (i.e. instance) to be indexed like an array.

Let us understand indexers with one real-time example.

Create a console application. Add a class file with the name Employee.cs and then copy and paste the following code.

namespace IndexersDemo
{
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public double Salary { get; set; }
    }
}

Now create another class file with the name Company.cs and then copy and paste the following code into the class.

using System.Collections.Generic;
using System.Linq;
namespace IndexersDemo
{
    public class Company
    {
        //Create a varibale to hold a list of employees
        private List<Employee> listEmployees;

        //Through the constructor initialize the listEmployees variable
        public Company()
        {
            listEmployees = new List<Employee>();

            listEmployees.Add(new Employee
            { EmployeeId = 101, Name = "Pranaya", Gender = "Male", Salary = 1000 });
            listEmployees.Add(new Employee
            { EmployeeId = 102, Name = "Preety", Gender = "Female", Salary = 2000 });
            listEmployees.Add(new Employee
            { EmployeeId = 103, Name = "Anurag", Gender = "Male", Salary = 5000 });
            listEmployees.Add(new Employee
            { EmployeeId = 104, Name = "Priyanka", Gender = "Female", Salary = 4000 });
            listEmployees.Add(new Employee
            { EmployeeId = 105, Name = "Hina", Gender = "Female", Salary = 3000 });
            listEmployees.Add(new Employee
            { EmployeeId = 106, Name = "Sambit", Gender = "Male", Salary = 6000 });
            listEmployees.Add(new Employee
            { EmployeeId = 107, Name = "Tarun", Gender = "Male", Salary = 8000 });
            listEmployees.Add(new Employee
            { EmployeeId = 108, Name = "Santosh", Gender = "Male", Salary = 7000 });
            listEmployees.Add(new Employee
            { EmployeeId = 109, Name = "Trupti", Gender = "Female", Salary = 5000 });
        }
        
        // The indexer takes an employeeId as parameter
        // and returns the employee name
        public string this[int employeeId]
        {
            get
            {
                return listEmployees.
                    FirstOrDefault(x => x.EmployeeId == employeeId).Name;
            }
            set
            {
                listEmployees.
                    FirstOrDefault(x => x.EmployeeId == employeeId).Name = value;
            }
        }
    }
}
Explanation of the above code:

In the Company class constructor, we are initializing the variable listEmployees by adding employees to the list.

We then created an indexer by using the “this” keyword. The above indexer takes the employeeId as the parameter and returns that employee name.

Just like properties indexers have the get and set accessors. The get accessor is used to return the value whereas the set accessor is used to assign a value.

Let see how to use the above indexer. Create another class with the Main method and then copy and paste the below code.

using System;
namespace IndexersDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Company company = new Company();

            Console.WriteLine("Name of Employee with Id = 101: " + company[101]);
            Console.WriteLine();
            Console.WriteLine("Name of Employee with Id = 105: " + company[105]);
            Console.WriteLine();
            Console.WriteLine("Name of Employee with Id = 107: " + company[107]);

            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("Changing the names of employees with Id = 101,105,107");
            Console.WriteLine();

            company[101] = "Employee 101 Name Changed";
            company[105] = "Employee 105 Name Changed";
            company[107] = "Employee 107 Name Changed";

            Console.WriteLine("Name of Employee with Id = 101: " + company[101]);
            Console.WriteLine();
            Console.WriteLine("Name of Employee with Id = 105: " + company[105]);
            Console.WriteLine();
            Console.WriteLine("Name of Employee with Id = 107: " + company[107]);
            
            Console.ReadLine();
        }
    }
}
Points to remember:

The EmployeeId’s 101,105 and107 are passed into the company object to retrieve the respective employee names. To retrieve the names of the employees, here the “get” accessor of the indexer is used.

Similarly To change the names of the employees, here the set accessor of the integral indexer defined on Company class is used.

company[101] = “Employee 101 Name Changed”;

company[105] = “Employee 105 Name Changed”;

company[107] = “Employee 107 Name Changed”;

So when we run the application, it gives us the following output.

Indexers Real-Time Example in C#.

Notice that because of the “employeeId” indexer, now we are able to use the company object like an array. 

Overloading the Indexer

We can also overload the indexers in C#. Let us understand this with an example.

As of now, we have an integer indexer in the Company class. Now let us create another indexer based on the string parameter in the company class.

Indexers Real-Time Example in C#.

The important point to keep in mind is that the indexers are overloaded based on the number and type of parameters.

The complete code of the Company class is given below.
using System.Collections.Generic;
using System.Linq;
namespace IndexersDemo
{
    public class Company
    {
        //Create a varibale to hold a list of employees
        private List<Employee> listEmployees;

        //Through the constructor initialize the listEmployees variable
        public Company()
        {
            listEmployees = new List<Employee>();

            listEmployees.Add(new Employee
            { EmployeeId = 101, Name = "Pranaya", Gender = "Male", Salary = 1000 });
            listEmployees.Add(new Employee
            { EmployeeId = 102, Name = "Preety", Gender = "Female", Salary = 2000 });
            listEmployees.Add(new Employee
            { EmployeeId = 103, Name = "Anurag", Gender = "Male", Salary = 5000 });
            listEmployees.Add(new Employee
            { EmployeeId = 104, Name = "Priyanka", Gender = "Female", Salary = 4000 });
            listEmployees.Add(new Employee
            { EmployeeId = 105, Name = "Hina", Gender = "Female", Salary = 3000 });
            listEmployees.Add(new Employee
            { EmployeeId = 106, Name = "Sambit", Gender = "Male", Salary = 6000 });
            listEmployees.Add(new Employee
            { EmployeeId = 107, Name = "Tarun", Gender = "Male", Salary = 8000 });
            listEmployees.Add(new Employee
            { EmployeeId = 108, Name = "Santosh", Gender = "Male", Salary = 7000 });
            listEmployees.Add(new Employee
            { EmployeeId = 109, Name = "Trupti", Gender = "Female", Salary = 5000 });
        }
        
        // The indexer takes an employeeId as parameter
        // and returns the employee name
        public string this[int employeeId]
        {
            get
            {
                return listEmployees.
                    FirstOrDefault(x => x.EmployeeId == employeeId).Name;
            }
            set
            {
                listEmployees.
                    FirstOrDefault(x => x.EmployeeId == employeeId).Name = value;
            }
        }

        public string this[string gender]
        {
            get
            {
                // Returns the total count of employees whose gender matches
                // with the gender that is passed in.
                return listEmployees.Count(x => x.Gender.ToLower() == gender.ToLower()).ToString();
            }
            set
            {
                // Changes the gender of all employees whose gender matches
                // with the gender that is passed in.
                foreach (Employee employee in listEmployees)
                {
                    if (employee.Gender == gender)
                    {
                        employee.Gender = value;
                    }
                }
            }
        }
    }
}

Notice that, now the Company class has 2 indexers. The first indexer has an integer (employeeId) parameter and the second indexer has got a string (gender) parameter.

To test the string indexer, that we have just created, copy and paste the following code in the Main method of the Program class as shown below.

using System;
namespace IndexersDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Company company = new Company();
            Console.WriteLine("Before changing the Gender of all the male employees to Female");
            Console.WriteLine();

            // Get accessor of string indexer is invoked to return the total count of male employees
            Console.WriteLine("Total Number Employees with Gender = Male:" + company["Male"]);
            Console.WriteLine();
            Console.WriteLine("Total Number Employees with Gender = Female:" + company["Female"]);
            Console.WriteLine();
            
            // Set accessor of string indexer is invoked to change the gender all "Male" employees to "Female"
            company["Male"] = "Female";

            Console.WriteLine("After changing the Gender of all male employees to Female");
            Console.WriteLine();
            Console.WriteLine("Total Employees with Gender = Male:" + company["Male"]);
            Console.WriteLine();
            Console.WriteLine("Total Employees with Gender = Female:" + company["Female"]);
            
            Console.ReadLine();
        }
    }
}

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

Indexers Real-Time Example in C#

In the next article, we will discuss Enums in C# with examples.

SUMMARY:

In this article, I try to explain Indexers Real-Time Example in C#. 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 *