Important Update
The Guide Feature will be discontinued after December 15th, 2023. Until then, you can continue to access and refer to the existing guides.
Author avatar

Dániel Szabó

Overload Indexers in C#

Dániel Szabó

  • Jan 8, 2020
  • 9 Min read
  • 9,152 Views
  • Jan 8, 2020
  • 9 Min read
  • 9,152 Views
Languages Frameworks and Tools
C#

Introduction

In C# we have many different data structures available that allow us to store and retrieve specific data when needed. This guide will discuss indexers, and especially how to overload them the right way. When we talk about indexer overloading, the idea is to force the class to behave like a data structure, keep track of its instances, and allow us to retrieve those instances as we would do with an array or list.

We will first explore the topic of indexers, then turn our sights towards their overloading.

Indexers

This feature in C# allows you to index as class or struc as you would do it with an array. When we define an indexer for a class, we force it to behave like a virtual array. The array access operator, or [], can be used to access instances of a class that implements the indexer. The user is able to get or set the indexed value without pointing to an instance or a type member. The indexers are very similar to properties, but the main difference is that accessors to the indexers will take parameters, while properties cannot.

There is a general or template syntax for this, which looks as follows.

1type this[type_index index]
2{
3   get
4   {
5       // get the instance value from index
6   }
7   set
8   {
9       // set the instance value at index
10   }
11}
csharp

Let's take a practical example.

1using System;
2
3namespace ndexers
4{   
5    class Program
6    {
7        class Students
8        {            
9            private string[] _indexers = new string[10];
10            public string this[int index]
11            {
12                get { return _indexers[index]; }
13                set { _indexers[index] = value; }
14            }
15
16        }
17        static void Main(string[] args)
18        {
19            Students elementarySchool = new Students();
20            elementarySchool[0] = "Daniel";
21            elementarySchool[1] = "Florian";
22            elementarySchool[2] = "David";
23            for (int i = 0; i < 10; i++)
24            {
25                Console.WriteLine($" The student's name : {elementarySchool[i]}");
26            }
27            Console.ReadKey();
28            }
29    }
30}
csharp

Executing the app gives us the following output.

1The student's name : Daniel
2 The student's name : Florian
3 The student's name : David
4 The student's name :
5 The student's name :
6 The student's name :
7 The student's name :
8 The student's name :
9 The student's name :
10 The student's name :
bash

What happens here? We have a class called Students behaving like a virtual array and allowing up to ten student names to be stored. In the Main, the class is instantiated and three student names are inserted. Then a for loop is used to run through the elements.

If we set or access the following element.

1elementarySchool[10] = "Anya";
csharp

The result would be the following.

1System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
bash

This is due to the array-like behavior and the fact that in the class it is set to have 10 elements.

Now that we know how to cause our class to behave like an array, we can find out how to overload these indexers and add extra functionality.

Some important points:

  1. There are two types of indexers, one- and two-dimensional.
  2. Indexers can be overloaded.
  3. They are not equal to properties.
  4. Indexers allow the object to be indexed.
  5. Setting accessor will assign get and retrieve value.
  6. The value keyword is used when you set the value.
  7. Indexers are referred to as smart arrays or parameterized properties. though the latter might be misleading.
  8. Indexers cannot be static members as they are instance members of the class.

Overloading Indexers

The idea of overloading indexers is to imbue them with multiple arguments that allow us to support different datatypes. You can have different types of indexes—it's not mandatory to always use int. Multiple types allow you to build in flexibility and further increase the fault tolerance and robustness of the class and application. In order to achieve this, we need to declare it with multiple parameters, and each parameter should have different data types. The technique for the overload is very similar to the method for overloading. The very act of overloading is a C# feature intended to support one of the three pillars of object-oriented programming, or polymorphism.

Let's take a practical example.

1using System;
2
3namespace ndexers
4{   
5    class Program
6    {
7        class Guides
8        {            
9            private string[] _guideNames = new string[10];
10            
11            public string this[int index]
12            {
13                get { return _guideNames[index]; }
14                set { _guideNames[index] = value; }
15            }
16            
17            public string this[float id]
18            {
19                get { return _guideNames[1]; }
20                set { _guideNames[1] = value; }
21            }
22
23            public string this[double id]
24            {
25                get { return "This is read only"; }
26                set { }
27            }
28        }
29        static void Main(string[] args)
30        {
31            Guides writtenGuides = new Guides();
32            double k = 10.0;
33            writtenGuides[0] = "Written ";
34            writtenGuides[1.0f] = "Guides";
35            Console.WriteLine(writtenGuides[k]);
36            Console.WriteLine(writtenGuides[0]);
37            Console.WriteLine(writtenGuides[0] + writtenGuides[1.0f]);
38            Console.ReadKey();
39            }
40    }
41}
csharp

The output from the app is the following.

1This is read only
2Written
3Written Guides
bash

Let's look at what's happening under the hood. In our class Guides, we have three indexers. One is working with argument type int, another is with argument type float, and the third, which is read-only, is working with the double argument type. Read-only accessors are used when you want to prevent modification to an indexer of a specific type. Basically, the setter is not defined, and this is how you make it read-only. The indexer reacts to different types of indexes appropriately, and this is why we see the int argument returns Written, the float argument returns the concatenation of the int and float-based indexes, and the double notifies us that it's read only.

Finally, let's take a look at multi-dimensional indexers.

1using System;
2
3namespace ndexers
4{   
5    class Program
6    {
7        class MultiDimensional
8        {            
9            private string[,] _guideNames = new string[10,10];
10            
11            public string this[int x, int y]
12            {
13                get { return _guideNames[x,y]; }
14                set { _guideNames[x,y] = value; }
15            }            
16        }
17        static void Main(string[] args)
18        {
19            MultiDimensional theMatrix = new MultiDimensional();
20            theMatrix[0,0] = "Daniel";
21            theMatrix[0, 1] = "Florian";
22            for(int i = 0; i < 10; i++)
23            {
24                for(int j = 0; j < 10; j++)
25                {
26                    if( theMatrix[i,j] == null) { Console.Write("N.A. "); }
27                    else{ Console.Write($"{theMatrix[i, j]} "); }                    
28                }
29                Console.WriteLine();
30            }
31            Console.ReadKey();
32            }
33    }
34}
csharp

The output is as follows.

1Daniel Florian N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A.
2N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A.
3N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A.
4N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A.
5N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A.
6N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A.
7N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A.
8N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A.
9N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A.
10N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A. N.A.
bash

Here we have the MultiDimensional class, which implements a 10-by-10 matrix that allows you to store strings based on the indexes you specify. There is nothing special about this. It works as other multidimensional arrays would, and the bonus is the class context, which allows you to add extra functionality. We instantiate our class, add some items, then iterate over with nested for loops.

Conclusion

All in all, indexers and their overloading allow us to extend class functionality. This guide has shown you three distinct applications: the simple, single type-based indexers; how to overload indexers; and multi-dimensional indexers. The latter also supports overriding so you can build in extra functionality. I hope this has been informative for you and you found what you were looking for. If you liked this guide, make sure you give it a thumbs up.