Steven Spielberg
Steven Spielberg

Reputation:

What is the meaning of this C# code and how do I use it?

public int this[int x, int y]
{
   get { return (x + y); }
}

Upvotes: 8

Views: 389

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273844

It is an indexer, and that code is probably incorrect. You would normally see:

public int this[int x, int y]
{
    get { return (x * ColSize + y); }
}

class TheMatrix<T>
{
    private int _rows, _cols;
    private T[] _data;
    public TheMatrix(int rows, int cols)
    {
        _rows = rows;
        _cols = cols;
        _data = new T[_rows * _cols];
    }

    T this[int r, int c]
    {
        get { return _data[r * _cols + c]; }
        set { _data[r * _cols + c] = value; }
    }
}

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 839224

It's an indexer that accepts two integers. You can think of it as similar to a two dimensional array, except that the result is calculated on the fly instead of being stored.

It allows you to write int result = foo[a, b];

Upvotes: 20

Related Questions