Open In App

C# Indexers

Last Updated : 25 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C#, an indexer allows an instance of a class or struct to be indexed as an array. When an indexer is defined for a class, then that class will behave like a virtual array. Array access operator i.e. ([ ]) is used to access the instance of the class which uses an indexer. A user can retrieve or set the indexed value without pointing to an instance or a type member. The main difference between Indexers and Properties is that the accessors of the indexers (get and set) take parameters, whereas properties do not.

Syntax:

[Access_modifier] [Return_type] this [Parameter_list]
{
get

{ // get block code }

set

{ // set block code }
}

In the above syntax,

  • Access_Modifier: Specifies accessibility (e.g., public, private, protected, or internal).
  • Return_Type: Specifies the data type of the value the indexer will return.
  • this: Keyword that refers to the current instance of the class.
  • Parameter_List: Specifies the parameters used to index the class.
  • get and set: Accessors used to retrieve and assign values.

Example: This example demonstrates how to implement a simple indexer in a class.

C#
// Use of Indexers in C#
using System;

class Geeks
{
    private string[] values = new string[3];

    // Indexer declaration
    public string this[int index]
    {
        // Getter
        get
        {
            return values[index];
        }
        // Setter
        set
        {
            values[index] = value;
        }
    }
}

class Program
{
    static void Main()
    {
        Geeks o = new Geeks();

        // Assign values using the indexer
        o[0] = "C";
        o[1] = "C++";
        o[2] = "C#";

        // Access values using the indexer
        Console.WriteLine("First value: " + o[0]);
        Console.WriteLine("Second value: " + o[1]);
        Console.WriteLine("Third value: " + o[2]);
    }
}

Output
First value: C
Second value: C++
Third value: C#

Explanation: In the above example, the class Geeks uses an indexer to store and retrieve string values. Values are assigned and accessed using array-like syntax (o[0], o[1], etc.).

Implementing Indexers

  • Multiple-Index Parameters: Indexers can use multiple parameters for complex indexing, enabling access to elements based on various criteria.
  • Indexer Overloading: Indexers can be overload like methods allows multiple indexers with varying parameter types or counts to access elements in a class or struct.
  • Read-Only Indexers: Omitting the set accessor in an indexer makes it read-only, enabling value retrieval while preventing modifications.
  • Implicit vs. Explicit Interface: Indexers can be implemented implicitly or explicitly when defined as part of an interface. Implicit implementation is used when the indexer is defined within the class itself, while explicit implementation is used when the indexer is implemented explicitly to resolve any naming conflicts.
  • Indexers in Collections: Indexers are commonly used in collection classes, such as dictionaries, lists, and arrays.Can access and manipulate elements within these collections based on an index or key.
  • Custom Classes: Indexers can be implemented in custom classes to provide customized access to class members based on an index. Allows for more intuitive and expressive interaction with instances of the class.

Example: This example shows an indexer with multiple parameters to perform different operations.

C#
// C# Multi-Parameter Indexer
using System;

public class Indexer
{
	private int[] data = new int[10];

	// Indexer with multiple parameters
	public int this[int index, bool square]
	{
		get
		{
			if (square)
				return data[index] * data[index];
			else
				return data[index];
		}
		set
		{
			if (square)
				data[index] = (int)Math.Sqrt(value);
			else
				data[index] = value;
		}
	}

	// Overloaded indexer with string parameter
	public int this[string n]
	{
		get
		{
			switch (n.ToLower())
			{
				case "first":
					return data[0];
				case "last":
					return data[data.Length - 1];
				default:
					throw new 
                      ArgumentException("Invalid index parameter.");
			}
		}
	}

	// Read-only indexer
	public int this[int index]
	{
		get { return data[index]; }
	}
}

public class Geeks
{
	public static void Main()
	{
		Indexer i = new Indexer();

		// Setting values using multiple parameter indexer
		i[0, false] = 5;
		i[1, false] = 10;
		i[2, false] = 15;
		i[3, false] = 20;

		// Getting values using multiple parameter indexer
		Console.WriteLine(i[0, false]);
		Console.WriteLine(i[1, true]);

		// Getting values using string parameter indexer
		Console.WriteLine(i["first"]);
		Console.WriteLine(i["last"]);

		// Getting values using read-only indexer
		Console.WriteLine(i[2]);
	}
}

Output
5
100
5
0
15

Explanation: In the above example we creat a indexer which can perform different operations and can take multiple type parameters.

Key Points:

  • There are two types of Indexers i.e.
  • This enables the object to be indexed in a similar way to arrays.
  • A set accessor will always assign the value while the get accessor will return the value.
  • “this” keyword is always used to declare an indexer.
  • To define the value being assigned by the set indexer, ” value” keyword is used.
  • Indexers are also known as the Smart Arrays or Parameterized Property in C#.
  • Indexer can’t be a static member as it is an instance member of the class.

Next Article
Article Tags :

Similar Reads