Multi-parameter indexers let you access data using more than one key, like looking up a value by row and column in a table.
0
0
Multi-parameter indexers in C Sharp (C#)
Introduction
When you want to access elements in a grid or matrix using two numbers.
When you have a collection that needs two keys to find an item, like a calendar with year and month.
When you want to simplify code that uses multiple keys to get or set values.
When you want to make your class behave like a 2D array or table.
Syntax
C Sharp (C#)
public returnType this[type1 index1, type2 index2] { get { /* return value based on index1 and index2 */ } set { /* set value based on index1 and index2 */ } }
The keyword this defines the indexer.
You can use any number of parameters separated by commas inside the square brackets.
Examples
Indexer for a 2D integer matrix using row and column.
C Sharp (C#)
public int this[int row, int col] { get { return matrix[row, col]; } set { matrix[row, col] = value; } }
Indexer that looks up a person by first and last name.
C Sharp (C#)
public string this[string firstName, string lastName] { get { return FindPerson(firstName, lastName); } }
Sample Program
This program creates a 3x3 table and sets values at two positions using the multi-parameter indexer. Then it prints those values.
C Sharp (C#)
using System; class Table { private int[,] data = new int[3, 3]; public int this[int row, int col] { get { return data[row, col]; } set { data[row, col] = value; } } } class Program { static void Main() { Table table = new Table(); table[0, 0] = 10; table[1, 2] = 20; Console.WriteLine(table[0, 0]); Console.WriteLine(table[1, 2]); } }
OutputSuccess
Important Notes
Multi-parameter indexers make your class easier to use when working with multi-key data.
Indexers can have only get, only set, or both get and set accessors.
Be careful with index bounds to avoid runtime errors.
Summary
Multi-parameter indexers let you use more than one key to access data.
They make classes behave like multi-dimensional arrays or tables.
Use them to simplify code that needs multiple keys to find values.