![]() |
VOOZH | about |
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.
Example 1: This example shows Multidimensional Indexers using get and set accessors.
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.
public DataType this[DataType row, DataType column]
{
get { return data[row, column]; }
set { data[row, column] = value; }
}
Example 2: Demonstration of Multidimensional Indexer using only get(Read-Only) accessor.
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.
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.
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.