c sharp

How to Implement and Use Indexers in C#

C# indexers allows the instances of a class or a struct to be indexed like an array. This helps to enhance the way in which we access the elements within an object.

The best way is to think of them as a way of transforming an object into an array which allows us to access the elements using their indexes.

You will find the indexers in a wide variety of C# collections such as lists, dictionaries, etc.

In this brief tutorial, we will cover the fundamentals of working with indexers in C# classes.

Creating an Indexer

In C#, we can create an indexer using the “this” keyword followed by a list of parameters. The type of indexer is direct to the type of elements that you wish to access within the collection.

The following shows the basic syntax for creating a simple indexer:

public int this[int index]
{
    get { return array[index]; }
    set { array[index] = value; }
}

Example:

Take the following example that defines a class with a simple “get” and “set” accessors to assign and retrieve the values:

public class ExampleIndexer
{
    private int[] array;

    public ExampleIndexer(int size)
    {
        array = new int[size];
    }
    public int this[int index]
    {
        get { return array[index]; }
        set { array[index] = value; }
    }
}

In this case, we define a basic class that encapsulates an integer array. Using an indexer, we allow an external access to the elements of the private field.

We can then access or modify the elements of the array using an object of the class as if it was an actual array.

ExampleIndexer sample = new ExampleIndexer(5);
sample[0] = 100;
sample[1] = 200;
Console.WriteLine(sample[0]);

As you can see, we use the object of the class like a normal array.

We can also use an indexer of strings. Take the following example:

public class ExampleIndexer
{
    private Dictionary<string, string> dictionary = new Dictionary<string, string>();

    public string this[string key]
    {
        get { return dictionary[key]; }
        set { dictionary[key] = value; }
    }
}

In this case, we use a Dictionary to store the values. We also create an indexer of string type which enables us to access the elements using a string key which is similar to a typical dictionary element access.

Conclusion

In this tutorial, we explored the basic functionality of indexers in C#, their use, and how to implement them. Check the docs for more details.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list