VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/c-sharp-multidimensional-indexers/

⇱ C# Multidimensional Indexers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C# Multidimensional Indexers

Last Updated : 11 Jul, 2025

In C#, indexers are special members that allow objects to be indexed similarly to arrays. Multi-dimensional indexers in C# are the same as multidimensional arrays. We can efficiently retrieve data with a multi-dimensional indexer by providing at least two parameters in its declaration. The first indexes the row dimension, the second indexes the column dimension, and so on.

  • Easy to implement multidimensional indexers in custom collections. We can easily use it to build custom operations.
  • We can define custom logic in the get and set accessors of the indexer to access or modify elements
  • Access elements using integer subscripts, each indexing a dimension

Example 1: This example shows Multidimensional Indexers using get and set accessors.


Output
1	2	3
4	5	6
7	8	9

Explanation: In the above example, we use a multidimensional indexer to access and modify elements in a 2D array. The get accessor retrieves values from the array, while the set accessor assigns values. The program fills the array and prints a 3x3 matrix.

Syntax of Multidimensional Indexer

public DataType this[DataType row, DataType column]

{
get { return data[row, column]; }
set { data[row, column] = value; }
}

  • get Accessor: It is used to retrieve the value at the defined indices.
  • set Accessor: It is used to assign a value to the defined indices.

Example 2: Demonstration of Multidimensional Indexer using only get(Read-Only) accessor.


Output
1	2	3	
2	3	4	
3	4	5	

Explanation: In the above example, we use a read-only multidimensional indexer where the get accessor returns the sum of the given row and column indices. The program iterates over the indices and prints the calculated values in a tabular format.

Example 3: Demonstration of Multidimensional Indexer using only set accessor to modify elements.


Output
3

Explanation: In the above example, we use a multidimensional indexer with only a set accessor to assign values to a 2D array. The program sets specific values and retrieves one element to demonstrate the assignment operation.

Example 4: Custom Logic in the Get Accessor

In this example, we demonstrate how to incorporate custom logic in the get accessor of a multi-dimensional indexer. Let’s consider a scenario where we want to return a specific element based on the provided indices.


Output
10
20
30

Explanation: In the above example, we use a multidimensional indexer with a custom get accessor that returns predefined values (10, 20, 30) for specific indices. If the indices do not match predefined cases, it returns -1. This demonstrates how to apply conditional logic inside an indexer.

Comment
Article Tags:

Explore