C# Indexers – Indexers VS Properties in C#

In this post, we will learn about indexers in C# using a few examples. We’ll also look at the key difference between the indexer and properties in C#.

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

 

What are Indexers in C#?

An Indexer in C# is a smart property that allows an instance of a class or struct to be indexed as a virtual array.
It is defined in the same way as properties, the only difference being that the indexer is defined using this keyword and square brackets []. An Indexer allows you to retrieve the data members of a class by using the index position.
Index positions can be integers, strings, characters, etc.

Syntax

The following is the syntax for defining an indexer in C#.

[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
    }
}
SyntaxDescription
AccessModifier:Access modifiers can be public, private, protected, or internal.
ReturnType:It can be any valid C# type like string, integer, object, etc.
this:this keyword is used to point 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 indexer in C#?

The following example defines an indexer in the class.

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

Looking at the example above, we have 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 running the above program.

indexers program result
Result of the above Indexer program.

C# Overload Indexer

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.

Overloaded Indexer in C 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#, the Property can be static or an instance member.
3. An indexer in C# can be accessed through the index positionProperty can be accessed 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 is 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

FAQs

Q: What are the benefits of indexers in C#?

1. It supports overloading for any user defines array in C#.
2. They are used for overloading an [ ] operator.

Q: Why do we use indexers in C#?

Indexers allow you to create a class, struct or interface that client applications can access as an array.

Q: How is the indexer different from property C#?

Indexers in C# are always declared as instance members, never as static members.

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#
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments