Return link to double in C #?

I am new to C # and I am trying to implement a matrix class. I want to have a function in (i, j) that will support setting up and receiving data, that is, I would like to be able to use it both for M.at(i,j)=5.0and for if (M.at(i,j)>3.0). In C ++, I would write this as follows:

double& at(i,j) {
   return data[i * cols+ j];
}

What would the same function look like in C #? I read several topics, for example Is it possible to return a variable reference in C #? but I do not want to use a wrapper.

+4
source share
1 answer

What you are looking for is an indexer :

public class Matrix
{
    public double this[int i, int j]
    {
        get
        {
            return internalStorage[i, j];
        }
        set
        {
            internalStorage[i, j] = value;
        }
    }
}

And you consume it like this:

var matrix = new Matrix();
if (matrix[i, j] > 3.0)
{
    // double at index i, j is bigger than 3.0
}

matrix[i, j] = 5.0;
+6
source

Source: https://habr.com/ru/post/1614942/


All Articles