Search code examples
c#matrixindices

How to do a double indexer for an own class object in C#


I have done a new class to define a N-Dimensional Matrix in C#, however if I want to access to its elements and I dont know how to proceed more than 1 index. The elements are stored in an array of double arrays.

private class MatrixND
{
    private double[][] elements;
    public MatrixND()
    {
        elements = new double[N][];
    }
}

Usually, to access to the index in the own class I add the following method to the class:

public double this[int index]
{
    get
    {
        return elements[index];
    }
    set
    {
        elements[index] = value;
    }
}

Which would work if it was a simple array of doubles, then calling the index [i] where i can be any number from 0 to the lenght of the array, would return a double.

How I can do the same but for my matrix case so I can call mymatrix[index1][index2] and get a double?

Thank you very much!


Solution

  • If you use public double this[int x, int y] then caller's can access obj[7, 12] etc. However, to access obj[7][12] would need the first indexer to return a type that itself has another indexer - maybe a struct that simply holds the parent instance and the first index value, effectively deferring the full lookup until the second index is supplied.


    Something like:

    public sealed class MatrixND
    {
        private const int N = 42; // or a a.ctor arg, whatever
        private double[][] elements;
        public MatrixND()
        {
            elements = new double[N][];
        }
    
        public Indexer this[int x] => new(this, x);
    
        public readonly struct Indexer(MatrixND parent, int x)
        {
            public double this[int y]
            {
                get => parent.elements[x][y];
                set => parent.elements[x][y] = value;
            }
        }
    }