C# › Indexers & Operator Overloading

How would you implement a multi-dimensional indexer, like a Matrix class supporting matrix[row, col] syntax?

Advanced

Answer

Declare the indexer with multiple parameters separated by commas inside 'this[...]', exactly like a multi-parameter method — this lets your custom type support natural 2D (or higher-dimensional) index access syntax matching a built-in rectangular array's [,] syntax.
public class Matrix {
  private readonly double[,] _data;
  public Matrix(int rows, int cols) { _data = new double[rows, cols]; }
  public double this[int row, int col] {
    get => _data[row, col];
    set => _data[row, col] = value;
  }
}
var m = new Matrix(3, 3);
m[0, 1] = 5.0;
Real-world example Building a custom Matrix, Grid, or 2D game board class that supports natural [row, col] access syntax.

Common follow-ups: How would you additionally support a RANGE-based indexer, like matrix[0..2, ..] for slicing?