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.
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); }
}
}
Do you mean something like this?
array[x][y]
Where x is the row and y is the column.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With