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

In this article, we will learn about the indexers in C# through a few examples. In addition, we will see what is the main difference between indexer 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.
Indexers can be defined in the same way as property but the only difference is that the indexer can be defined using this keyword and square brackets [ ].

An indexer turns a class into a virtual array, allowing us to access the class’s data members by using the index position.
An integer, a string, a character, and so on can all be used as index positions.

Syntax to define Indexer in C#

The following is the syntax for defining an indexer using this keyword and the 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.

How to 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 the “Employees” array list. Here, in the Program class, we are using the “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#

In C#, the indexer can be overloaded. With multiple index types like string, integer, and others, we can create overloaded Indexers.
If there are scenarios where we need to retrieve objects using a string or a numeric value, we can use overloaded indexers.
Take a look at the example below, which shows how to overload 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.

Comparison Between Properties and Indexers 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.

C# 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. Indexer 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

Indexers in Interfaces

An Interface can have indexers declared, but the get and set accessors of an indexer are left empty in the interface.
An interface indexer accessor might look something like this:

Example- Indexer declaration in Interface

public interface IInterface
{  
    //C# Indexer declaration in Interface:
    string this[int index]
    {
        get;
        set;
    }
}

References MSDN: Indexers

Conclusion:

In this article, we learned about indexers and properties in C# with examples. I hope you enjoyed this post and found it useful. If you have any questions or suggestions, please post comments below.

Recommended Articles

    1. 10 Difference between interface and abstract class In C#
    2. C# Struct vs Class
    3. C# List Class |Top 12 Amazing Generic List Methods
    4. IEnumerable Interface in C# with examples
    5. Constructors in C# with Examples
    6. C# Enum | How To Play With Enum in C#?
    7. Generic Delegates in C# With Examples
    8. C# Dictionary with Examples
    9. Multithreading in C#

Leave a Reply