4

I'm new to C# and I'm trying to implement a matrix class. I want to have a function at(i,j) which would support setting and getting data i.e. I would like to be able to use it for both M.at(i,j)=5.0 and if (M.at(i,j)>3.0). In C++ I would write it like this:

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

How would the same function look in C#? I've read some topics like Is it Possible to Return a Reference to a Variable in C#? but I don't want to use a wrapper.

Community
  • 1
  • 1
Alex Fish
  • 768
  • 6
  • 18

1 Answers1

6

What you're 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;
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321