Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D array property

Is it possible to write a property for a 2D array that returns a specific element of an array ? I'm pretty sure I'm not looking for an indexer because they array belongs to a static class.

like image 242
Andrew Avatar asked Feb 24 '23 02:02

Andrew


2 Answers

It sounds like you want a property with parameters - which is basically what an indexer is. However, you can't write static indexers in C#.

Of course you could just write a property which returns the array - but I assume you don't want to do that for reasons of encapsulation.

Another alternative would be to write GetFoo(int x, int y) and SetFoo(int x, int y, int value) methods.

Yet another alternative would be to write a wrapper type around the array and return that as a property. The wrapper type could have an indexer - maybe just a readonly one, for example:

public class Wrapper<T>
{
    private readonly T[,] array;

    public Wrapper(T[,] array)
    {
        this.array = array;
    }

    public T this[int x, int y]
    {
        return array[x, y];
    }

    public int Rows { get { return array.GetUpperBound(0); } }
    public int Columns { get { return array.GetUpperBound(1); } }
}

Then:

public static class Foo
{
    private static readonly int[,] data = ...;

    // Could also cache the Wrapper and return the same one each time.
    public static Wrapper<int> Data
    {
        get { return new Wrapper<int>(data); }
    }
}
like image 76
Jon Skeet Avatar answered Mar 07 '23 13:03

Jon Skeet


Do you mean something like this?

array[x][y]

Where x is the row and y is the column.

like image 43
WEFX Avatar answered Mar 07 '23 13:03

WEFX