What is Indexer in C#?| Indexers VS Properties in C#

In this article, we will learn about the ‘Indexer in C#‘ with multiple examples. Also, we will see what are the major difference between the ‘Indexers and Properties in C#‘.

image-Indexer-in-C#
Indexers in C#

What is Indexer in C#?

Indexer in C# is a smart property that allows an instance of a class or struct to be indexed as a virtual array.
An indexer can be defined the same way as property but the only difference is, the indexer can be defined using this keyword and square brackets [].

Indexers will make a class behave like a virtual array. We can start accessing the data members of a class with the help of the index position.
Index position can be an integer, string, char, etc.

Syntax to define ‘Indexer in C#

Following is the syntax of defining an indexer using this keyword and index operator [].

[AccessModifier] [ReturnType] this[ParameterType parameter]
{
    get
    {
        // Return specified index value from the internal collection.
    }
    set
    {
        // Set a value at the specified index in an internal collection
    }
}
    • AccessModifier: Access modifier can be public, private, protected or internal.
    • ReturnType: It can be any valid C# type like string , integer, object, etc.
    • this: this keyword is use to points to the object of the current class.
    • Parameter: This specifies the parameter of the indexer.
    • get{ } and set { }: These are the getter and setter methods to retrieve and set the values.

Implement an ‘indexers in C#

The following example will demonstrate the concept of Indexer in C#

using System;
using System.Collections;

namespace Indexers
{
    class Employees
    {
        // Declare properties
        public int Id { get; set; }
        public string Name { get; set; }
   
        private ArrayList employeeArray = new ArrayList();

        // Define the indexer

        public Employees this[int index]
        {
            get { return (Employees)employeeArray[index]; }

            set { employeeArray.Insert(index,value); }
        }

        public int TotalCount => employeeArray.Count;
    }


    class Program
    {
        static void Main(string[] args)
        {
            Employees employees = new Employees();

            // Adding objects using indexer
            employees[0] = new Employees() { Id = 101, Name = "Shekh Ali" };
            employees[1] = new Employees() { Id = 102, Name = "Mark Adam" };
            employees[2] = new Employees() { Id = 103, Name = "Huberto Batiz" };

            // Get and print each item using indexer

            for(int index =0;index < employees.TotalCount; index ++)
            {
                Console.WriteLine($"Id: {employees[index].Id} , Name: {employees[index].Name}");
            }
        }
    }
}

If you look at the above example, we implemented an indexer in the Employees class to access the internal collection of “Employees” array list. Here, in Program class, we are using “Employees” class object “employees” as an array to add or retrieve the employee’s data.

We will get the following result after executing the above program.

indexers program result
Result of the above Indexer program.

Overloading ‘Indexer in C#

Indexer in C# can be overloaded. We can create overloaded Indexers with different index types such as String, Integer, etc.
If there is a scenario when we want to access the items using string or the numeric value, In that case, we can go for overloaded indexers.
Let’s take a look at the following example of overloading an indexer with different index types.

using System;
using System.Collections;

namespace Indexers
{
    class Employees
    {
        // string array to store data
        private string[] strArray = new string[5];

    
        // Define integer type indexer
        public string this[int index]
        {
            get
            {            
                return strArray[index];
            }
            set
            {
                strArray[index] = value;
            }
        }

        // Define string type indexer
        public string this[string name]
        {
            get
            {
                foreach (string item in strArray)
                {
                    if ( string.Equals(item,name,StringComparison.OrdinalIgnoreCase))
                        return item.ToUpper();
                }
                return null;
            }
        }   
    }


    class Program
    {
        static void Main(string[] args)
        {
            Employees employees = new Employees();

            // Adding string value into indexer
            employees[0] = "Shekh Ali" ;
            employees[1] = "Mark Adam" ;
            employees[2] = "Huberto Batiz" ;
            employees[3] = "Janet Manzanares";
            employees[4] = "Shikha Sharma";

            // Get and print each item using indexer
            Console.WriteLine($"*** Accessing Indexer with integer type ***");

            for (int index =0;index < 5; index ++)
            {
                Console.WriteLine($"Name: {employees[index]}");
            }


            // Accessing Indexer with string type
            Console.WriteLine($"*** Accessing Indexer with string type ***");
            Console.WriteLine($"Name: {employees["Shekh Ali"]}");
            Console.WriteLine($"Name: {employees["Mark Adam"]}");
        }
    }
}

The indexer methods for the “Employees” class have two overloads, one that takes an integer value and another that takes a string value. We can have as many overloads as we would like, just like we would for the overloaded methods we define in the classes.

Once we execute the above program, we will get the following result.

Difference between Indexers and Properties in C#

Indexers in C# are very similar to properties. Except for the differences shown in the following table, all the rules that are defined for property accessors will also apply to indexers.

IndexersProperties
1. Indexers in C# are created using this keyword and square brackets [].Properties in C# don’t require this keyword to be created.
2. Indexers must be an instance member of a class.In C#, Property can be static or an instance member.
3. An indexer in C# can be accessed through the index positionProperty can be access by its name.
4. In C#, Indexers can be overloaded.In C#, Properties don’t support overloading.
5. Indexers are declared with at least one parameter.Properties in C# are always declared without having any parameters.
6. Indexer allows an element of an internal collection to be called using index position.Allow accessing private fields of a class via public property
Difference between Indexers and Properties in C#.

To read more about properties, please visit Properties In C# with examples

Recommended Articles

  1. 10 Difference between interface and abstract class In C#
  2. IEnumerable Interface in C# with examples
  3. Constructors in C# with Examples
  4. C# Enum | How To Play With Enum in C#?
  5. Exception Handling in C#| Use of try, catch and finally block
  6. Generic Delegates in C# With Examples

Conclusion:

In this article, we learned about indexers and properties in C# with examples. I hope you enjoyed this post and found it useful. In case you have any doubt, please post your feedback, question, or comments.

Thanks for visiting. 🙂

Leave a Reply